arnaucube
arnaucube/comunicationLeapPublic Self-hosted repository
comunicationLeap/node_modules/shortid/lib/alphabet.js
node_modules/shortid/lib/alphabet.jsRaw
 1'use strict';
 2
 3var randomFromSeed = require('./random/random-from-seed');
 4
 5var ORIGINAL = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-';
 6var alphabet;
 7var previousSeed;
 8
 9var shuffled;
10
11function reset() {
12    shuffled = false;
13}
14
15function setCharacters(_alphabet_) {
16    if (!_alphabet_) {
17        if (alphabet !== ORIGINAL) {
18            alphabet = ORIGINAL;
19            reset();
20        }
21        return;
22    }
23
24    if (_alphabet_ === alphabet) {
25        return;
26    }
27
28    if (_alphabet_.length !== ORIGINAL.length) {
29        throw new Error('Custom alphabet for shortid must be ' + ORIGINAL.length + ' unique characters. You submitted ' + _alphabet_.length + ' characters: ' + _alphabet_);
30    }
31
32    var unique = _alphabet_.split('').filter(function(item, ind, arr){
33       return ind !== arr.lastIndexOf(item);
34    });
35
36    if (unique.length) {
37        throw new Error('Custom alphabet for shortid must be ' + ORIGINAL.length + ' unique characters. These characters were not unique: ' + unique.join(', '));
38    }
39
40    alphabet = _alphabet_;
41    reset();
42}
43
44function characters(_alphabet_) {
45    setCharacters(_alphabet_);
46    return alphabet;
47}
48
49function setSeed(seed) {
50    randomFromSeed.seed(seed);
51    if (previousSeed !== seed) {
52        reset();
53        previousSeed = seed;
54    }
55}
56
57function shuffle() {
58    if (!alphabet) {
59        setCharacters(ORIGINAL);
60    }
61
62    var sourceArray = alphabet.split('');
63    var targetArray = [];
64    var r = randomFromSeed.nextValue();
65    var characterIndex;
66
67    while (sourceArray.length > 0) {
68        r = randomFromSeed.nextValue();
69        characterIndex = Math.floor(r * sourceArray.length);
70        targetArray.push(sourceArray.splice(characterIndex, 1)[0]);
71    }
72    return targetArray.join('');
73}
74
75function getShuffled() {
76    if (shuffled) {
77        return shuffled;
78    }
79    shuffled = shuffle();
80    return shuffled;
81}
82
83/**
84 * lookup shuffled letter
85 * @param index
86 * @returns {string}
87 */
88function lookup(index) {
89    var alphabetShuffled = getShuffled();
90    return alphabetShuffled[index];
91}
92
93module.exports = {
94    characters: characters,
95    seed: setSeed,
96    lookup: lookup,
97    shuffled: getShuffled
98};