Skip to content
This repository was archived by the owner on Apr 4, 2019. It is now read-only.

Commit 6830264

Browse files
author
Godhuda
committed
Create a mechanism for generating a random id
This will be used to give each template a unique, serializable id.
1 parent 63171f0 commit 6830264

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

packages/htmlbars-compiler/lib/utils.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
/*globals window:false*/
2+
/*globals Uint8Array:false*/
3+
14
export function processOpcodes(compiler, opcodes) {
25
for (var i=0, l=opcodes.length; i<l; i++) {
36
var method = opcodes[i][0];
@@ -9,3 +12,28 @@ export function processOpcodes(compiler, opcodes) {
912
}
1013
}
1114
}
15+
16+
let lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
17+
var generateId;
18+
19+
if (typeof window !== 'undefined' && window.crypto) {
20+
generateId = function() {
21+
let buf = new Uint8Array(12);
22+
window.crypto.getRandomValues(buf);
23+
24+
buf = buf.map(i => i % 64);
25+
return [].slice.call(buf).map(i => lookup.charAt(i)).join('');
26+
};
27+
} else {
28+
generateId = function() {
29+
let buf = [];
30+
31+
for (let i=0; i<12; i++) {
32+
buf.push(lookup.charAt(Math.floor(Math.random() * 64)));
33+
}
34+
35+
return buf.join('');
36+
};
37+
}
38+
39+
export { generateId };
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import { generateId } from '../htmlbars-compiler/utils';
2+
3+
QUnit.module('generating a template ID');
4+
5+
QUnit.test('generates a different ID every time', function() {
6+
let seen = Object.create(null);
7+
8+
for (let i=0; i<1000; i++) {
9+
seen[generateId()] = true;
10+
}
11+
12+
equal(Object.keys(seen).length, 1000, '1000 different ids were generated');
13+
});

0 commit comments

Comments
 (0)