Published
Edited
Dec 7, 2021
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
cook = (list) => list
.split("\n")
.map(
k =>
(
([direction, amount]) => ({direction, amount: +amount})
)
(k.split(" "))
)
Insert cell
cook(testcourse)
Insert cell
cooked = cook(raw)
Insert cell
final = (course, depth = 0, horizontal = 0) =>
course
.reduce(
(accu, {direction, amount}) => {
direction === "up"
? depth -= amount
: direction === "down"
? depth += amount
: direction === "forward"
? horizontal += amount
: null;
return depth * horizontal
},
0
)
Insert cell
assert(final(cooked), 1815044, "Part 1: Input data fails.")
Insert cell
assert(final(cook(testcourse)), 150, "Part 1: Test data fails.")
Insert cell
Insert cell
Insert cell
aimer = (course, depth = 0, horizontal = 0, aim = 0) =>
course
.reduce(
(_, {direction, amount}) => {
if (direction === "forward") {
horizontal += amount;
depth += amount * aim;
} else if (direction === "down") {
aim += amount;
} else if (direction === "up") {
aim -= amount;
}
return depth * horizontal
},
0
)
Insert cell
assert(aimer(cook(testcourse)), 900, "Part 2 test data failed.")
Insert cell
assert(aimer(cooked), 1739283308, "Part 2: Input data fails.")
Insert cell
Insert cell
aimer2 = (course, horizontal = 0, depth = 0, aim = 0) => {
// pluck the proper function from the object literal and call it
// NB modifies function’s global variables!
const switcher = ({
"forward": function (amount) {horizontal += amount; depth += amount * aim;},
"up": function (amount) {aim -= amount;},
"down": function (amount) {aim += amount;},
});
course.forEach(({direction, amount}) => (switcher[direction])(amount));
return depth * horizontal;
}
Insert cell
assert(aimer2(cook(testcourse)), 900, "Part 2: Aimer2 Test data fails.")
Insert cell
assert(aimer2(cooked), 1739283308, "Part 2: Aimer2 Input data fails.")
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
assert(final(cook(testcourse)), 150, "Test course failed")
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