-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscramble.js
81 lines (63 loc) · 2.32 KB
/
scramble.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 swapPositions = (password, x, y) => {
const scrambledPassword = [...password];
scrambledPassword[parseInt(x)] = password[parseInt(y)];
scrambledPassword[parseInt(y)] = password[parseInt(x)];
return scrambledPassword;
};
const swapLetters = (password, x, y) => {
const scrambledPassword = password;
const previousX = password.indexOf(x);
const previousY = password.indexOf(y);
scrambledPassword[previousX] = y;
scrambledPassword[previousY] = x;
return scrambledPassword;
};
const rotate = (password, direction, steps) => {
steps = (direction === 'left' ? -1 : 1) * parseInt(steps);
steps = (steps % password.length + password.length) % password.length;
return [
...password.slice(password.length - steps),
...password.slice(0, password.length - steps),
];
};
const rotateByPosition = (password, x) => {
const index = password.indexOf(x);
const steps = 1 + index + (index >= 4 ? 1 : 0);
return rotate(password, 'right', steps);
};
const reversePositions = (password, x, y) => {
return [
...password.slice(0, parseInt(x)),
...password.slice(parseInt(x), parseInt(y) + 1).reverse(),
...password.slice(parseInt(y) + 1),
];
};
const movePositions = (password, x, y) => {
const scrambledPassword = [...password];
const character = scrambledPassword.splice(parseInt(x), 1)[0];
scrambledPassword.splice(parseInt(y), 0, character);
return scrambledPassword;
};
const commands = [
{ pattern: /swap position (\d) with position (\d)/, fn: swapPositions },
{ pattern: /swap letter (\w) with letter (\w)/, fn: swapLetters },
{ pattern: /reverse positions (\d) through (\d)/, fn: reversePositions },
{ pattern: /rotate (left|right) (\d) step/, fn: rotate },
{ pattern: /move position (\d) to position (\d)/, fn: movePositions },
{ pattern: /rotate based on position of letter (\w)/, fn: rotateByPosition },
];
module.exports = (input, seed = 'abcdefgh') => {
const instructions = input
.split('\n')
.map((line) => {
for (let i = 0; i < commands.length; i++) {
if (commands[i].pattern.test(line)) {
return [commands[i].fn, line.match(commands[i].pattern).slice(1)];
}
}
});
const initialPassword = seed.split('');
return instructions
.reduce((password, [fn, args]) => fn(password, ...args), initialPassword)
.join('');
};