human-readable-ids.js/index.js

66 行
1.5 KiB
JavaScript

/*jshint -W054 */
;(function (exports) {
'use strict';
var lists = exports.humanReadableIds || require('./lists')
, shuffle = exports.knuthShuffle || require('knuth-shuffle').knuthShuffle
, animals = []
, adjectives = []
, numbers = []
;
function genNumbers() {
var i = 2
;
numbers = [];
numbers.push(0);
// 1 is not plural, so we skip it
for (i = 2; i <= 100; i += 1) {
numbers.push(i);
}
return shuffle(numbers);
}
function populate() {
if (!adjectives.length) {
adjectives = shuffle(lists.adjectives.slice(0));
}
if (!animals.length) {
animals = shuffle(lists.animals.slice(0));
}
if (!numbers.length) {
numbers = shuffle(genNumbers());
}
}
function random() {
populate();
return adjectives.pop()
+ '-' + animals.pop()
+ '-' + numbers.pop()
;
}
// Accepts a format as a stirng of 'a' for adjective, 'n' for noun, and '#' for number
function get(format) {
populate();
hri = new Array();
for (var i = 0; i < format.length; i++) {
switch (format[i]) {
case 'a': hri.push(adjectives.pop()); break;
case 'n': hri.push(animals.pop()); break;
case '#': hri.push(adjectives.pop()); break;
default:
throw 'Unexpected value ' + format[i] + '. Expected a,n,#';
}
return hri.join('-');
}
exports.humanReadableIds = { random: random };
exports.hri = exports.humanReadableIds;
}('undefined' !== typeof exports && exports || new Function('return this')()));