Public
Edited
May 25, 2022
Insert cell
Insert cell
myPoints = [
[10, 10],
[15, 10],
[20, 20]
]
Insert cell
Insert cell
function totalCost1(locations) {
let total = 0;
let prev = locations[0];

for (let i = 0; i < locations.length; i++) {
total += cost(prev, locations[i]);
prev = locations[i];
}
return total;
}
Insert cell
function cost([x0, y0], [x1, y1]) {
return Math.abs(x0 - x1) + Math.abs(y0 - y1);
}
Insert cell
totalCost1(myPoints)
Insert cell
Insert cell
function totalCost2(locations) {
const cost = ([x0, y0], [x1, y1]) => Math.abs(x0 - x1) + Math.abs(y0 - y1);
let total = 0;
let prev = locations[0];

for (let i = 0; i < locations.length; i++) {
total += cost(prev, locations[i]);
prev = locations[i];
}
return total;
}
Insert cell
totalCost2(myPoints)
Insert cell
Insert cell
Insert cell
Insert cell
function totalCost3(locations) {
const cost = ([x0, y0], [x1, y1]) => Math.abs(x0 - x1) + Math.abs(y0 - y1);

return locations.reduce(
([total, prev], current) => [total + cost(prev, current), current], // Reducing function
[0, locations[0]] // Initial total and 'previous' values
)[0];
}
Insert cell
totalCost3(myPoints)
Insert cell
Insert cell
Insert cell
Insert cell
function totalCost4(
locations,
cost = ([x0, y0], [x1, y1]) => Math.abs(x0 - x1) + Math.abs(y0 - y1)
) {
return locations.reduce(
([total, prev], loc) => [total + cost(prev, loc), loc],
[0, locations[0]]
)[0];
}
Insert cell
Insert cell
totalCost4(myPoints)
Insert cell
Insert cell
totalCost4(myPoints, (p1, p2) => Math.hypot(...p1, ...p2))
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more