forked from EntropyString/JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcharSet.js
More file actions
62 lines (53 loc) · 1.45 KB
/
charSet.js
File metadata and controls
62 lines (53 loc) · 1.45 KB
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
import lcm from './lcm'
class CharSet {
constructor(chars) {
this.chars = chars
this.len = chars.length
this.entropyPerChar = Math.floor(Math.log2(this.len))
if (this.entropyPerChar != Math.log2(this.len)) {
throw new Error('EntropyString only supports CharSets with a power of 2 characters')
}
this.charsPerChunk = lcm(this.entropyPerChar, 8) / this.entropyPerChar
}
use(chars) {
const len = chars.length
// Ensure correct number of characters
if (len != this.len) {
throw new Error('Invalid character count')
}
// Ensure no repeated characters
for (let i = 0; i < len; i++) {
let c = chars.charAt(i)
for (let j = i+1; j < len; j++) {
if (c === chars.charAt(j)) {
throw new Error('Characters not unique')
}
}
}
this.chars = chars
}
}
const charSet64 =
new CharSet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_")
const charSet32 =
new CharSet("2346789bdfghjmnpqrtBDFGHJLMNPQRT")
const charSet16 =
new CharSet("0123456789abcdef")
const charSet8 =
new CharSet("01234567")
const charSet4 =
new CharSet("ATCG")
const charSet2 =
new CharSet("01")
const isValid = (charSet) => {
return charSet instanceof CharSet
}
export default {
charSet64: charSet64,
charSet32: charSet32,
charSet16: charSet16,
charSet8: charSet8,
charSet4: charSet4,
charSet2: charSet2,
isValid: isValid
}