Skip to content

Instantly share code, notes, and snippets.

@draeton
Created August 8, 2012 05:50
Show Gist options
  • Save draeton/3292541 to your computer and use it in GitHub Desktop.
Save draeton/3292541 to your computer and use it in GitHub Desktop.
Test implementation for ES6 Name module
(function (undefined) {
"use strict";
const MIN_STR_LEN = 0x10;
const MAX_STR_LEN = 0xF0 - MIN_STR_LEN;
const MIN_CHAR_CODE = 0x0;
const MAX_CHAR_CODE = 0xFFFF - MIN_CHAR_CODE;
/**
* Return an array of length length
*/
let arrayOfLength = function (length) {
return new Array(length + 1).join(" ").split("");
};
/**
* Return a random number between upper and lower
*/
let randomNumber = function (lower, upper) {
return Math.round(Math.random() * upper + lower);
};
/**
* Return a random char between min and max char codes
*/
let randomChar = function () {
return String.fromCharCode(randomNumber(MIN_CHAR_CODE, MAX_CHAR_CODE));
};
/**
* Return a random string of length length
*/
let randomString = function (length) {
return arrayOfLength(length).map(randomChar).join("");
};
/**
* Constructor for private read-only names. toString returns generated value
*/
let Name = this.Name = function () {
let value = randomString(randomNumber(MIN_STR_LEN, MAX_STR_LEN)) + (+new Date());
return {
toString: function () {
return value;
}
};
};
}).call(this);
(function (undefined) {
"use strict";
// testing collisions
let o = {};
let n = "";
let i = 0;
let z = 500;
while (o[n = new Name()] === undefined && i < z) {
o[n] = true;
i++;
}
if (i === z) {
console.log("no collisions; count === " + i);
} else {
console.log("collision at " + i + "; max(" + z + ")");
}
}).call(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment