-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.js
71 lines (61 loc) · 2.68 KB
/
utils.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
65
66
67
68
69
70
71
/* jshint node: true */
'use strict';
const DEFAULT_PALETTE_OPTIONS = {
'blackAndWhite': false,
'greys': 'auto',
'shades': 'auto',
'shuffle': false
};
const shuffleArray = (a) => {
const CUTOFF = a.length % 22 + 1,
MASK = 0xffffff & a.length << 16 + a.length << 8 + a.length;
const HASH = (n) => MASK & n << CUTOFF + (n >> 24 - CUTOFF);
return a.slice().sort((x, y) => {
if (HASH(x) > HASH(y))
return -1;
if (HASH(x) < HASH(y))
return +1;
return 0;
});
};
const randomiseArray = (a) => {
const RESULT = a.slice();
let tmp, x;
for (let i = 0; i < RESULT.length; i++) {
x = Math.floor(Math.random() * RESULT.length);
tmp = RESULT[x];
RESULT[x] = RESULT[i];
RESULT[i] = tmp;
}
return RESULT;
};
const checkPaletteParams = (n, opts) => {
if (!Number.isInteger(n) || 2 > n)
return new Error('superscript.Palette: “n” must be an integer ≥ 2');
for (const i in opts)
if ('blackAndWhite' === i) {
if (false !== opts[i] && true !== opts[i])
return new Error('superscript.Palette: “blackAndWhite” must be either “false” or “true”');
} else if ('greys' === i) {
if (false !== opts[i] && true !== opts[i] && 'auto' !== opts[i])
return new Error('superscript.Palette: “greys” must be either “false”, “true” or “auto”');
} else if ('shades' === i) {
if (false !== opts[i] && true !== opts[i] && 'auto' !== opts[i] && (!Number.isInteger(opts[i]) || 1 > opts[i]))
return new Error('superscript.Palette: “shades” must be either “false”, “true”, “auto” or an integer ≥ 1');
} else if ('shuffle' === i) {
if (false !== opts[i] && true !== opts[i] && 'random' !== opts[i])
return new Error('superscript.Palette: “shuffle” must be either “false”, “true” or “random”');
} else
return new Error(`superscript.Palette: “${i}” is not a valid option`);
if (opts.blackAndWhite && true === opts.greys && 3 > n)
return new Error('superscript.Palette: “blackAndWhite” and “greys” cannot be both “true” when “n” < 3');
if (opts.blackAndWhite && true === opts.shades && 4 > n)
return new Error('superscript.Palette: “blackAndWhite” and “shades” cannot be both “true” when “n” < 4');
if (opts.shades + (opts.blackAndWhite ? 2 : 0) < n)
return new Error(`superscript.Palette: the palette is too small to include ${opts.shades} shades${opts.blackAndWhite ? ' plus black and white' : ''}`);
return false;
};
exports.DEFAULT_PALETTE_OPTIONS = DEFAULT_PALETTE_OPTIONS;
exports.shuffleArray = shuffleArray;
exports.randomiseArray = randomiseArray;
exports.checkPaletteParams = checkPaletteParams;