Skip to content

Commit 41d9d9a

Browse files
refactor: remove switch statement
1 parent 770fa68 commit 41d9d9a

File tree

1 file changed

+21
-29
lines changed

1 file changed

+21
-29
lines changed

src/helpers/aerArmonBase.js

Lines changed: 21 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -3,28 +3,24 @@ const encode = (input, options) => {
33
throw Error('Key is too short! It must be at least 3 characters')
44
}
55

6-
const heyKey = [...options.key].map(toHexCharCodeConcatenationNumber)
6+
const hexKey = [...options.key].map(toHexCharCodeConcatenationNumber)
77

88
const chunkedString = input.match(new RegExp(`.{1,${Math.round(options.key.length / 2)}}`, 'g'))
99

1010
const keyLengthRange = Array.from(new Array(options.key.length), (v, i) => i)
1111

1212
return chunkedString.map(s =>
1313
keyLengthRange.reduce((acc, i) => {
14-
switch (i % (options.isAer256 ? 3 : 4)) {
15-
case 0:
16-
acc += heyKey[i]
17-
break
18-
case 1:
19-
acc /= heyKey[i]
20-
break
21-
case 2:
22-
acc -= heyKey[i]
23-
break
24-
case 3:
25-
acc *= 0.01 * heyKey[i]
26-
}
27-
return acc
14+
const OPERATION_LOOKUP = [
15+
(v, k) => v + k,
16+
(v, k) => v / k,
17+
(v, k) => v - k,
18+
(v, k) => v * (0.01 * k)
19+
]
20+
21+
const modifier = i % (options.isAer256 ? 3 : 4)
22+
23+
return OPERATION_LOOKUP[modifier](acc, hexKey[i])
2824
}, toHexCharCodeConcatenationNumber(s))
2925
).join(options.isAer256 ? ', ' : '+')
3026
}
@@ -41,20 +37,16 @@ const decode = (input, options) => {
4137
return input.split(options.isAer256 ? ', ' : '+').map(s => {
4238
// Reverse arithmetic from encoding based on parsed float from string
4339
const float = keyLengthRangeReversed.reduce((acc, i) => {
44-
switch (i % (options.isAer256 ? 3 : 4)) {
45-
case 0:
46-
acc -= hexKey[i]
47-
break
48-
case 1:
49-
acc *= hexKey[i]
50-
break
51-
case 2:
52-
acc += hexKey[i]
53-
break
54-
case 3:
55-
acc /= 0.01 * hexKey[i]
56-
}
57-
return acc
40+
const OPERATION_LOOKUP = [
41+
(v, k) => v - k,
42+
(v, k) => v * k,
43+
(v, k) => v + k,
44+
(v, k) => v / (0.01 * k)
45+
]
46+
47+
const modifier = i % (options.isAer256 ? 3 : 4)
48+
49+
return OPERATION_LOOKUP[modifier](acc, hexKey[i])
5850
}, parseFloat(s))
5951

6052
// Round output and convert it to hex

0 commit comments

Comments
 (0)