Published
Edited
Dec 4, 2019
1 star
Insert cell
Insert cell
Insert cell
sum = (a,b) => a + b
Insert cell
sumArray = xs => xs.reduce(sum)
Insert cell
fuelcalc = mass => Math.floor(mass / 3) - 2
Insert cell
solution1 = xs => sumArray(xs.map(fuelcalc))
Insert cell
solution1(data)
Insert cell
Insert cell
function recursiveAddFuel (x) {
const tally = Array.isArray(x) ? x : [x] // if not array, convert to array
const add = fuelcalc(tally[tally.length-1]) // pluck last value and get fuel cost
return add > 0 ? recursiveAddFuel(tally.concat(add)) : tally
}
Insert cell
solution2 = xs =>
xs
.map(fuelcalc)
.map(recursiveAddFuel)
.map(sumArray)
.reduce(sum)
Insert cell
solution2(data)
Insert cell
Insert cell
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