Published
Edited
Dec 8, 2021
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
directions_obj = directions.map(input => { return {command: input[0][0], n: +input[0][1]} })
Insert cell
Insert cell
to_coords = (data) => {
return data.map((x,i) => {
let to_num = +x.replace(/[^0-9\.]+/g, "")
let word = x.replace(/[0-9]/g, '').trim()
switch (word) {
case 'forward':
return {x: to_num, y:0}
break;
case 'down':
return {x: 0, y:to_num}
break;
case 'up':
return {x: 0, y:-to_num}
break;
default:
console.log(`You broke it.`);
}
})
}
Insert cell
coords = to_coords(raw)
Insert cell
reducer = (previousValue, currentValue) => previousValue + currentValue;
Insert cell
coords.map(x => { return x.x }).reduce(reducer, 0)
Insert cell
coords.map(x => { return x.y }).reduce(reducer, 0)
Insert cell
2018*820
Insert cell
Insert cell
{
let x = 0
let depth = 0
let aim = 0

directions
.forEach(([cmd, n]) => {
n = parseInt(n)
switch (cmd) {
case 'forward':
x += n
depth += aim * n
break;
case 'up':
aim -= n
break;
case 'down':
aim += n
break;
}
return {x,depth,aim}
})
return {x,depth,aim}
}
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