Created
February 19, 2012 21:09
-
-
Save JakubOboza/1865787 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
crypto = require('crypto') | |
exec = require('child_process').exec | |
chomp = () -> | |
this.replace(/(\n|\r)+$/, '') | |
String.prototype.chomp = chomp | |
class UidGenerator | |
constructor: () -> | |
rollUid: () -> | |
shasum = crypto.createHash('sha1') | |
shasum.update(process.getuid().toString()) | |
millis = new Date().getTime() - 1262304000000; | |
millis = millis * Math.pow(2, 12) | |
id2 = Math.random() * Math.pow(2, 8) | |
uid = millis + id2 + Math.random() | |
shasum.update(uid.toString()) | |
return shasum.digest('hex'); | |
systemUuid: (callback) => | |
exec 'uuid', (err, stdout, stderr) -> | |
callback(stdout.chomp()) | |
# specs | |
module.exports = UidGenerator; | |
module.exports.ready = new UidGenerator(); | |
if process.env['NODE_ENV'] and process.env['NODE_ENV'].toLowerCase() == 'test' | |
require('should') | |
describe "uid generator", () -> | |
generator = new UidGenerator() | |
it "should generate random uids", () -> | |
left = generator.rollUid() | |
right = generator.rollUid() | |
left.should.not.equal(right) | |
describe 'uuid generator', () -> | |
generator = new UidGenerator() | |
it "should give back system uuid", (done) -> | |
generator.systemUuid (uuid) -> | |
generator.systemUuid (uuid2) -> | |
uuid.should.not.equal(uuid2) | |
done() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment