Allow custom format for random values #3

Open
Ghost wants to merge 2 commits from (deleted):master into master
3 changed files with 37 additions and 4 deletions

View File

@ -55,6 +55,9 @@ var i;
for (i = 0; i < 100; i += 1) { for (i = 0; i < 100; i += 1) {
console.log(hri.random()); console.log(hri.random());
} }
// Use custom pattern of number-noun-adjective
console.log(hri.get('#na'));
``` ```
### bower / browser ### bower / browser

View File

@ -7,11 +7,11 @@
, animals = [] , animals = []
, adjectives = [] , adjectives = []
, numbers = [] , numbers = []
; ;
function genNumbers() { function genNumbers() {
var i = 2 var i = 2
; ;
numbers = []; numbers = [];
numbers.push(0); numbers.push(0);
@ -23,7 +23,7 @@
return shuffle(numbers); return shuffle(numbers);
} }
function random() { function populate() {
if (!adjectives.length) { if (!adjectives.length) {
adjectives = shuffle(lists.adjectives.slice(0)); adjectives = shuffle(lists.adjectives.slice(0));
} }
@ -33,14 +33,40 @@
if (!numbers.length) { if (!numbers.length) {
numbers = shuffle(genNumbers()); numbers = shuffle(genNumbers());
} }
}
function random() {
populate();
return adjectives.pop() return adjectives.pop()
+ '-' + animals.pop() + '-' + animals.pop()
+ '-' + numbers.pop() + '-' + numbers.pop()
; ;
} }
exports.humanReadableIds = { random: random }; // Accepts a format as a stirng of 'a' for adjective, 'n' for noun, and '#' for number
function get(format) {
populate();
let hri = [];
for (let item of format) {
switch (item) {
case 'a':
hri.push(adjectives.pop());
break;
case 'n':
hri.push(animals.pop());
break;
case '#':
hri.push(numbers.pop());
break;
default:
throw 'Unexpected value ' + item + '. Expected a,n,#';
}
}
return hri.join('-');
}
exports.humanReadableIds = {random: random, get: get};
exports.hri = exports.humanReadableIds; exports.hri = exports.humanReadableIds;
}('undefined' !== typeof exports && exports || new Function('return this')())); }('undefined' !== typeof exports && exports || new Function('return this')()));

View File

@ -9,4 +9,8 @@
for (i = 0; i < 100; i += 1) { for (i = 0; i < 100; i += 1) {
console.log(hri.random()); console.log(hri.random());
} }
for (i = 0; i < 10; i += 1) {
console.log(hri.get('#na'));
}
}('undefined' !== typeof exports && exports || new Function('return this')())); }('undefined' !== typeof exports && exports || new Function('return this')()));