Published
Edited
Dec 6, 2021
Insert cell
Insert cell
Insert cell
parse = ( list ) => list.split('\n').map( line => line.split(' ') ).map( ( [ dir, units ] ) => [ dir, parseInt( units )] )
Insert cell
parse(testInput)
Insert cell
go = ( input ) => {
const commands = parse( input );
let horizPos = 0, depth = 0;
commands.forEach( ( [ dir, units] ) => {
switch (dir) {
case 'forward': horizPos += units; break;
case 'down': depth += units; break;
case 'up': depth -= units; break;
}
})
return { horizPos, depth, answer: horizPos * depth }
}
Insert cell
go( testInput )
Insert cell
Insert cell
Insert cell
go(input)
Insert cell
Insert cell
go2 = ( input ) => {
const commands = parse( input );
let horizPos = 0, depth = 0, aim = 0;
commands.forEach( ( [ dir, units] ) => {
switch (dir) {
case 'forward':
horizPos += units;
depth += aim * units;
break;
case 'down': aim += units; break;
case 'up': aim -= units; break;
}
})
return { horizPos, depth, aim, answer: horizPos * depth }
}
Insert cell
go2(testInput)
Insert cell
go2(input)
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