-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
76 lines (61 loc) · 1.99 KB
/
index.js
File metadata and controls
76 lines (61 loc) · 1.99 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
'use strict'
const zipfian = require('zipfian-integer')
const uniform = require('uniform-integer')
const lexint = require('lexicographic-integer')
const prb = require('pseudo-random-buffer')
const pmr = require('pseudo-math-random')
module.exports = function keyspace (n, options) {
options = options || {}
if (!Number.isInteger(n)) {
throw new TypeError('The first argument "n" must be an integer')
} else if (n < 0) {
throw new RangeError('The first argument "n" must be >= 0')
}
const randomBytes = prb(options.seed)
const prng = pmr(options.seed)
// Note: skew=0 also results in a uniform distribution.
const zipf = options.distribution === 'zipfian'
const skew = options.skew || 0
const sample = zipf ? zipfian(0, n - 1, skew, prng) : uniform(0, n - 1, prng)
const offset = options.offset || 0
// TODO: support randomized valueSizes
const valueSize = options.valueSize || 0
const generateValueSize = (fallback) => valueSize || fallback
const { keyAsBuffer, valueAsBuffer, keyAsNumber } = options
const keyGenerators = {}
const valueGenerators = {}
keyGenerators.random = function () {
return keyGenerators.seq(sample())
}
keyGenerators.seq = function (i) {
i += offset
if (keyAsNumber) {
return i
} else if (keyAsBuffer) {
return Buffer.from(lexint.pack(i))
} else {
return lexint.pack(i, 'hex')
}
}
keyGenerators.seqReverse = function (i) {
return keyGenerators.seq(n - i - 1)
}
valueGenerators.random = function () {
const size = generateValueSize(16)
if (valueAsBuffer) {
return randomBytes(size)
} else {
return randomBytes(size / 2 + 1).toString('hex').slice(0, size)
}
}
valueGenerators.empty = function () {
const size = generateValueSize(0)
return valueAsBuffer ? Buffer.alloc(size) : '0'.repeat(size)
}
return {
key: keyGenerators[options.keys || 'random'],
value: valueGenerators[options.values || 'random'],
keyGenerators,
valueGenerators
}
}