Skip to content

Commit

Permalink
feat(Utility): expose UUID generator
Browse files Browse the repository at this point in the history
ISSUES CLOSED: #91
  • Loading branch information
benjamincharity committed May 24, 2019
1 parent f323396 commit eb08352
Show file tree
Hide file tree
Showing 7 changed files with 103 additions and 24 deletions.
13 changes: 13 additions & 0 deletions ngx-tools/src/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ isArray([]); // Returns: true
- [`isString`](#isstring)
- [`arrayHasAllElementsSet`](#arrayhasallelementsset)
- [`VERSION`](#version)
- [UUID](#uuid)

<!-- END doctoc generated TOC please keep comment here to allow auto update -->

Expand Down Expand Up @@ -885,6 +886,18 @@ VERSION.patch // Returns: 3
```
### UUID
[[source]](uuid/uuid.ts)
Generate a canonically formatted UUID that is Version 1 through 5 and is the appropriate Variant as per RFC4122.
```typescript
import { generateUUID } from '@terminus/ngx-tools';

generateUUID(); // Returns a UUID such as: `f4ee5eed-ed19-3681-713e-907a23ed7858`
```
<!-- LINKS -->
Expand Down
37 changes: 37 additions & 0 deletions ngx-tools/src/uuid/uuid.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { uuidRegex } from '@terminus/ngx-tools/regex';

import { generateUUID } from './uuid';


describe(`uuid`, function() {
const testUUIDGenerator = function(generator: () => string, iterations = 1, done: jest.DoneCallback): Promise<void> {
const uuidstore: Record<string, string> = {};
let i;
let newUuid;

for (i = 0; i < iterations; i++) {
newUuid = generator();

// Test Validity
if (!uuidRegex.test(newUuid)) {
done.fail(new Error('This is the error'));
}

// Test Collision
if (uuidstore[newUuid]) {
done.fail(new Error(`Collision on ${newUuid}`));
}
uuidstore[newUuid] = newUuid;
}

return Promise.resolve();
};


test(`should create UUIDs that do not collide`, function(done) {
testUUIDGenerator(generateUUID, 100, done).then(() => {
done();
});
});

});
23 changes: 23 additions & 0 deletions ngx-tools/src/uuid/uuid.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/* eslint-disable no-magic-numbers */
/**
* Generate a canonically formatted UUID that is Version 1 through 5 and is the appropriate Variant as per RFC4122.
*
* @example
* generateUUID() // Returns: `f4ee5eed-ed19-3681-713e-907a23ed7858`
*
* @return The UUID
*/
export function generateUUID(): string {
const buf = new Uint16Array(8);
window.crypto.getRandomValues(buf);

const S4 = function(num: number) {
let ret = num.toString(16);
while (ret.length < 4) {
ret = `0${ret}`;
}
return ret;
};

return (`${S4(buf[0]) + S4(buf[1])}-${S4(buf[2])}-${S4(buf[3])}-${S4(buf[4])}-${S4(buf[5])}${S4(buf[6])}${S4(buf[7])}`);
}
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,8 @@
"tsickle": "^0.34.0",
"tslint": "^5.16.0",
"typescript": "~3.2.1",
"validate-commit-msg": "^2.14.0"
"validate-commit-msg": "^2.14.0",
"window-crypto": "^1.1.0"
},
"husky": {
"hooks": {
Expand Down
37 changes: 18 additions & 19 deletions tools/jest-global-mocks.ts
Original file line number Diff line number Diff line change
@@ -1,42 +1,42 @@
// Polyfill `window.crypto`
import 'window-crypto';

// tslint:disable no-any no-unsafe-any
const mock = () => {
let storage: Record<string, any> = {};
return {
getItem: (key: string): any => key in storage ? storage[key] : null,
getItem: (key: string): any => (key in storage ? storage[key] : null),
setItem: (key: string, value: any) => {
storage[key] = value || '';
return storage[key];
},
removeItem: (key: string) => delete storage[key],
clear: () => storage = {},
clear: () => (storage = {}),
};
};
// tslint:enable no-any no-unsafe-any

Object.defineProperty(window, 'localStorage', {value: mock()});
Object.defineProperty(window, 'sessionStorage', {value: mock()});
Object.defineProperty(window, 'getComputedStyle', {
value: () => ['-webkit-appearance'],
});
Object.defineProperty(window, 'getComputedStyle', {value: () => ['-webkit-appearance']});
Object.defineProperty(window, 'CSS', {value: () => ({})});




/**
* Patches for Material
*/
const WARN_SUPPRESSING_PATTERNS = [
/Could not find Angular Material core theme/,
/Could not find HammerJS/,
/Could not find Angular Material core theme/,
/Could not find HammerJS/,
];
// eslint-disable-next-line no-console
const warn = console.warn;
Object.defineProperty(console, 'warn', {
value: (...params: string[]) => {
if (!WARN_SUPPRESSING_PATTERNS.some((pattern) => pattern.test(params[0]))) {
warn(...params);
}
},
value: (...params: string[]) => {
if (!WARN_SUPPRESSING_PATTERNS.some(pattern => pattern.test(params[0]))) {
warn(...params);
}
},
});
Object.defineProperty(window, 'matchMedia', {
value: () => (
Expand All @@ -48,9 +48,8 @@ Object.defineProperty(window, 'matchMedia', {
),
});
Object.defineProperty(document.body.style, 'transform', {
value: () =>
({
enumerable: true,
configurable: true,
}),
value: () => ({
enumerable: true,
configurable: true,
}),
});
1 change: 1 addition & 0 deletions tslint.spec.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"extends": "@terminus/tslint-config-frontend/testing",
"rules" : {
"no-implicit-dependencies": false,
"no-non-null-assertion": false,
"prefer-on-push-component-change-detection": false
}
}
13 changes: 9 additions & 4 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -474,10 +474,10 @@
"@typescript-eslint/eslint-plugin-tslint" "^1.4.2"
"@typescript-eslint/parser" "^1.4.2"

"@terminus/ngx-tools@*":
version "6.7.0"
resolved "https://registry.yarnpkg.com/@terminus/ngx-tools/-/ngx-tools-6.7.0.tgz#6a5bcc41b9d8802669f3e030d3de835da2d77a17"
integrity sha512-bytDD9w6Rl6WilBRfvUwnp76HIB/U6LKYcycHJRlA3Fs98QRkSXgyPuh3uhN/yGxBB67JEGs78w9Uuxe79dcXg==
"@terminus/ngx-tools@^6.10.0":
version "6.10.0"
resolved "https://registry.yarnpkg.com/@terminus/ngx-tools/-/ngx-tools-6.10.0.tgz#d19da4e78ca489c189c8576f9db981cb0f7ce735"
integrity sha512-qxXupnVfj84gxSzk2AV/GvpS2EmGaA78mNiMlwhaY3s/CwB/3Bfe1+zCrhVBRzgyPUk0VDRcK3OSGng/efPHUQ==
dependencies:
tslib "^1.9.0"

Expand Down Expand Up @@ -12847,6 +12847,11 @@ widest-line@^2.0.0:
dependencies:
string-width "^2.1.1"

window-crypto@^1.1.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/window-crypto/-/window-crypto-1.1.0.tgz#1f4acfe4ddacabfb5b4bd6eda7d2fe63e4e0b288"
integrity sha512-KD5ucryy9RGf9Yb68ynEFTXv1DVxAjqn9FmTlFTW+G38rbMmkJ92+iEEmwMoNZShdy9K6PT6s3uE7imyiXcFWA==

windows-release@^3.1.0:
version "3.2.0"
resolved "https://registry.yarnpkg.com/windows-release/-/windows-release-3.2.0.tgz#8122dad5afc303d833422380680a79cdfa91785f"
Expand Down

0 comments on commit eb08352

Please sign in to comment.