Permalink
Browse files

fix negative number issue

  • Loading branch information...
1 parent 3ab1a57 commit 0c6923fb84ed9391f5ea2a18f6fafe517e5c48b6 @dylang committed Jan 12, 2012
Showing with 26 additions and 9 deletions.
  1. +25 −8 lib/shortid.js
  2. +1 −1 package.json
View
33 lib/shortid.js
@@ -3,7 +3,9 @@
* by Dylan Greene
*
*/
-var randomBytes = require('crypto').randomBytes
+var randomBytes = require('crypto').randomBytes;
+
+var DEBUG = false;
// Older (pre 0.6) versions of Node don't have a randomBytes function
if (!randomBytes) {
@@ -30,13 +32,22 @@ var options = {
var counter = -1;
var previousSeconds;
+function toString(buffer) {
+ var str = '';
+ var i;
+ for(i = 0; i < buffer.length; i++) {
+ str = str + ALPHABET_SHUFFLED[buffer[i]];
+ }
+ return str;
+}
+
/**
* Generate the id
* Returns a unique short id.
*/
function generate() {
- var seconds = Date.now() - LESS_TIME >> 10; //divide by 10 to get seconds
+ var seconds = Math.round((Date.now() - LESS_TIME) * 0.01); // using >> got us negative numbers somehow
counter = seconds == previousSeconds ? counter + 1 : 0;
@@ -53,20 +64,26 @@ function generate() {
}
encode(options.version);
+
+ DEBUG && console.log('just version', toString(buffer));
+
encode(options.worker);
+
+ DEBUG && console.log('worker', toString(buffer));
+
if (counter > 0) {
encode(counter);
+ DEBUG && console.log('counter', toString(buffer));
+
}
encode(seconds); //seconds since this module was created. >> 10 removes the milliseconds more or less.
+ DEBUG && console.log('seconds', toString(buffer), seconds);
+
previousSeconds = seconds;
- var str = '';
- var i;
- for(i = 0; i < buffer.length; i++) {
- str = str + ALPHABET_SHUFFLED[buffer[i]];
- }
- return str;
+ return toString(buffer);
+
}
/**
View
2 package.json
@@ -1,6 +1,6 @@
{
"name":"shortid",
- "version":"1.0.5",
+ "version":"1.0.6",
"description":"Amazingly short non-sequential url-friendly unique id generator.",
"keywords": ["short", "tiny", "id", "uuid", "bitly", "shorten", "mongoid", "shortid", "tinyid", "id"],
"homepage":"http://github.com/dylang/shortid",

0 comments on commit 0c6923f

Please sign in to comment.