/
index.js
64 lines (56 loc) · 1.12 KB
/
index.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
/**
* @param {string} base
* @returns {string[]}
*/
function decorateTree(base) {
const RULES = {
PP: 'P',
RR: 'R',
BB: 'B',
BP: 'R',
PB: 'R',
BR: 'P',
RB: 'P',
RP: 'B',
PR: 'B',
}
const getTopBase = function (base) {
const decorations = base.split(' ')
return decorations
.slice(1)
.map((decoration, index) => RULES[decorations[index] + decoration])
.join(' ')
}
const tree = [base]
while (base.length > 1) {
base = getTopBase(base)
tree.unshift(base)
}
return tree
}
/**
* @param {string} base
* @returns {string[]}
*/
function decorateTreeOptimized(base) {
const RULES = {
PP: 'P',
RR: 'R',
BB: 'B',
BP: 'R',
PB: 'R',
BR: 'P',
RB: 'P',
RP: 'B',
PR: 'B',
}
const getTopBase = base =>
Array.from(
{length: base.length - 1},
(_, index) => RULES[base[index] + base[index + 1]]
)
return [...Array(Math.floor(base.length / 2))]
.reduce(acc => (acc.unshift(getTopBase(acc[0])), acc), [base.split(' ')])
.map(row => row.join(' '))
}
export {decorateTree, decorateTreeOptimized}