-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchandrayaan.js
81 lines (65 loc) · 1.82 KB
/
chandrayaan.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
const {
moveDirectionMappings,
turnMappings,
oppositeMapping,
} = require("./constants");
const getNextPosition = (position, direction, movement) => {
const [x, y, z] = position;
const coordinateChange = moveDirectionMappings[direction][movement];
const newPosition = [
x + coordinateChange[0],
y + coordinateChange[1],
z + coordinateChange[2],
];
return newPosition;
};
const move = (chandrayaan, movement) => {
return {
...chandrayaan,
position: getNextPosition(
chandrayaan.position,
chandrayaan.direction,
movement
),
};
};
const turn = (chandrayaan, turnDirection) => {
const newDirection =
turnMappings[chandrayaan.direction][chandrayaan.facing][turnDirection];
return {
...chandrayaan,
direction: newDirection,
facing: chandrayaan.facing,
};
};
const apply = (command, state) => {
if (command === "f" || command === "b") {
return move(state, command);
}
if (command === "l" || command === "r") {
return turn(state, command);
}
// logic of u and d commands is derived from observation of
// movement of chandrayaan in 3-d space
if (command === "u") {
const newDirection = state.facing;
const newFacing = oppositeMapping[state.direction];
return { ...state, direction: newDirection, facing: newFacing };
}
if (command === "d") {
const newDirection = oppositeMapping[state.facing];
const newFacing = state.direction;
return { ...state, direction: newDirection, facing: newFacing };
}
};
const execute = (commands, state) => {
// commands is an array of commands e.g. ['f', 'b', 'l', 'r', 'u', 'd']
// inital state
let result = state;
for (const cmd of commands) {
// sent the updated state to the next command
result = apply(cmd, result);
}
return result;
}
module.exports = { execute };