From a3b8def77e211a7fd8f244666a0e1d3edacf0d16 Mon Sep 17 00:00:00 2001 From: Samuel Reed Date: Mon, 15 Dec 2014 09:00:31 +0100 Subject: [PATCH] Add two more url-safe characters to make the distribution even. --- index.js | 4 ++-- package.json | 3 +++ test.js | 36 ++++++++++++++++++++++++++++++++++++ 3 files changed, 41 insertions(+), 2 deletions(-) create mode 100644 test.js diff --git a/index.js b/index.js index 6240b30..29d9264 100644 --- a/index.js +++ b/index.js @@ -5,10 +5,10 @@ var crypto = require('crypto'); /** - * 62 characters in the ascii range that can be used in URLs without special + * 64 characters in the ascii range that can be used in URLs without special * encoding. */ -var UIDCHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; +var UIDCHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'; /** * Make a Buffer into a string ready for use in URLs diff --git a/package.json b/package.json index a4a113c..2629a4e 100644 --- a/package.json +++ b/package.json @@ -3,6 +3,9 @@ "description": "strong uid", "tags": ["uid"], "version": "0.0.3", + "scripts": { + "test": "node test.js" + }, "dependencies": { } } diff --git a/test.js b/test.js new file mode 100644 index 0000000..14439c2 --- /dev/null +++ b/test.js @@ -0,0 +1,36 @@ +'use strict'; +var uid = require('./index'); +var assert = require('assert'); + +var freqs = {}; +var ITERATIONS = 1000000; +var LENGTH = 64; +var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'; +var i; + +for (i = 0; i < chars.length; i++) { + freqs[chars[i]] = 0; +} + +console.log("Running", ITERATIONS, "iterations..."); + +while(ITERATIONS--) { + var str = uid(LENGTH); + for (var i = 0; i < str.length; i++) { + freqs[str[i]]++; + } +} + +console.log("Done. Distribution:"); +console.log(JSON.stringify(freqs, undefined, 2)); + +var vals = Object.keys(freqs).map(function(key) { + return freqs[key]; +}); +var min = Math.min.apply(null, vals); +var max = Math.max.apply(null, vals); + +console.log("Min freq:", min, "Max freq:", max); +var diffPcnt = Math.abs(min / max - 1) * 100; +console.log("Min and max frequencies are " + diffPcnt + "% apart."); +assert(diffPcnt < 1);