arnaucube
arnaucube/socketioMEANseedPublic Self-hosted repository
socketioMEANseed/server/node_modules/yeast/index.js
server/node_modules/yeast/index.jsRaw
 1'use strict';
 2
 3var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split('')
 4  , length = 64
 5  , map = {}
 6  , seed = 0
 7  , i = 0
 8  , prev;
 9
10/**
11 * Return a string representing the specified number.
12 *
13 * @param {Number} num The number to convert.
14 * @returns {String} The string representation of the number.
15 * @api public
16 */
17function encode(num) {
18  var encoded = '';
19
20  do {
21    encoded = alphabet[num % length] + encoded;
22    num = Math.floor(num / length);
23  } while (num > 0);
24
25  return encoded;
26}
27
28/**
29 * Return the integer value specified by the given string.
30 *
31 * @param {String} str The string to convert.
32 * @returns {Number} The integer value represented by the string.
33 * @api public
34 */
35function decode(str) {
36  var decoded = 0;
37
38  for (i = 0; i < str.length; i++) {
39    decoded = decoded * length + map[str.charAt(i)];
40  }
41
42  return decoded;
43}
44
45/**
46 * Yeast: A tiny growing id generator.
47 *
48 * @returns {String} A unique id.
49 * @api public
50 */
51function yeast() {
52  var now = encode(+new Date());
53
54  if (now !== prev) return seed = 0, prev = now;
55  return now +'.'+ encode(seed++);
56}
57
58//
59// Map each character to its index.
60//
61for (; i < length; i++) map[alphabet[i]] = i;
62
63//
64// Expose the `yeast`, `encode` and `decode` functions.
65//
66yeast.encode = encode;
67yeast.decode = decode;
68module.exports = yeast;