Skip to content

Commit 5be930e

Browse files
committed
Simplify bit shifts calc
Remove the two reverse() calls
1 parent ccc99c8 commit 5be930e

File tree

2 files changed

+21
-19
lines changed

2 files changed

+21
-19
lines changed

src/lib/bits.spec.ts

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,13 @@ test('Chars.Safe32', (t) => t.deepEqual(bitShifts(Chars.Safe32), [[32, 5]]))
1111

1212
test('Chars.AlphaNum', (t) => t.deepEqual(bitShifts(Chars.AlphaNum), [[62, 6]]))
1313

14+
test('Chars.Alpha', (t) =>
15+
t.deepEqual(bitShifts(Chars.Alpha), [
16+
[ 52, 6 ],
17+
[ 55, 5 ],
18+
[ 63, 3 ]
19+
]))
20+
1421
test('Chars.AlphaLower', (t) =>
1522
t.deepEqual(bitShifts(Chars.AlphaLower), [
1623
[26, 5],
@@ -31,5 +38,3 @@ test('Chars.SafeAscii', (t) =>
3138
[95, 5],
3239
[127, 2]
3340
]))
34-
35-
// test('Chars.AlphaNumLower', (t) => t.deepEqual(bitShifts(Chars.AlphaNumLower), [[62, 6]]))

src/lib/bits.ts

Lines changed: 14 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -42,23 +42,20 @@ const bitShifts = (chars: string): BitShifts => {
4242

4343
if (isPow2(chars.length)) return [baseBitShift]
4444

45-
const zeroBitShifts = new Array(nBitsPerChar)
46-
.fill(null)
47-
.reduce((acc, _n, ndx) => {
48-
acc.push(ndx)
49-
return acc
50-
}, [])
51-
.slice(2)
52-
.reverse()
53-
.reduce((shifts: BitShifts, bit: number) => {
54-
if (isBitZero(chars.length, bit)) {
55-
const shift: BitShift = [chars.length | (pow2(bit) - 1), nBitsPerChar - bit + 1]
56-
return shifts.concat([shift])
57-
}
58-
return shifts
59-
}, [])
60-
zeroBitShifts.push(baseBitShift)
61-
return zeroBitShifts.reverse()
45+
return new Array(nBitsPerChar)
46+
.fill(null)
47+
.reduce((acc, _n, ndx) => {
48+
acc.push(ndx)
49+
return acc
50+
}, [])
51+
.slice(2)
52+
.reduce((shifts: BitShifts, bit: number) => {
53+
if (isBitZero(chars.length, bit)) {
54+
const shift: BitShift = [chars.length | pow2(bit) - 1, nBitsPerChar - bit + 1]
55+
return shifts.concat([shift])
56+
}
57+
return shifts
58+
}, [baseBitShift])
6259
}
6360

6461
const valueAt = (lOffset: number, nBits: number, puidBytes: PuidBytes): number => {

0 commit comments

Comments
 (0)