Skip to content

Commit

Permalink
[minor] Generate different id's using toString
Browse files Browse the repository at this point in the history
  • Loading branch information
3rd-Eden committed Sep 2, 2015
1 parent 8972ea4 commit 66716fa
Showing 1 changed file with 3 additions and 40 deletions.
43 changes: 3 additions & 40 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,6 @@
'use strict';

var alphabet = [
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F',
'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z', '-', '_'
];

var length = alphabet.length
, map = {}
, seed = 0
, i = 0
var seed = 0
, prev;

/**
Expand All @@ -25,14 +11,7 @@ var length = alphabet.length
* @api public
*/
function encode(num) {
var encoded = '';

do {
encoded = alphabet[num % length] + encoded;
num = Math.floor(num / length);
} while (num > 0);

return encoded;
return num.toString(36);
}

/**
Expand All @@ -43,15 +22,7 @@ function encode(num) {
* @api public
*/
function decode(str) {
var decoded = 0
, i = 0;

while (i < str.length) {
decoded = decoded * length + map[str.charAt(i)];
i++;
}

return decoded;
return parseInt(str, 36);
}

/**
Expand All @@ -67,14 +38,6 @@ function yeast() {
return now +'.'+ encode(seed++);
}

//
// Map each character to its index.
//
while (i < length) {
map[alphabet[i]] = i;
i++;
}

//
// Expose the `yeast`, `encode` and `decode` functions.
//
Expand Down

2 comments on commit 66716fa

@lpinca
Copy link
Member

@lpinca lpinca commented on 66716fa Sep 2, 2015

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Originally it was using toString(), see https://github.com/unshiftio/yeast/blob/877fc57bcbb4c6b7cf03557b83c34c7cc1a95084/index.js, and this implementation is slightly faster and the library size is sligtly smaller, but the generted id is 8 bytes.

After the refactor the generated id is 7 bytes. We can speed up it a little by using Date.now() where available and by computing the modulus here like this: num & 63.

@3rd-Eden
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep, that's why i'm not merging this in to master.

Please sign in to comment.