Last active
July 2, 2019 15:55
-
-
Save MrGrigri/7e182fe5ac4f36b47ebc2cd568cc7e33 to your computer and use it in GitHub Desktop.
Simple Angular UUID management service. This ensures that a UUID is unique to the application by tracking all UUIDs in an app.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from '@angular/core'; | |
@Injectable({ | |
providedIn: 'root', | |
}) | |
export class IdService { | |
public ids: string[] = []; | |
constructor() {} | |
public generate(): string { | |
let isUnique = false; | |
let tempId = ''; | |
while (!isUnique) { | |
tempId = this.generator(); | |
if (!this.idExists(tempId)) { | |
isUnique = true; | |
this.ids.push(tempId); | |
} | |
} | |
return tempId; | |
} | |
public remove(id: string): void { | |
const index = this.ids.indexOf(id); | |
this.ids.splice(index, 1); | |
} | |
private generator(): string { | |
const isString = `${this.S4()}${this.S4()}-${this.S4()}-${this.S4()}-${this.S4()}-${this.S4()}${this.S4()}${this.S4()}`; | |
return isString; | |
} | |
private idExists(id: string): boolean { | |
return this.ids.includes(id); | |
} | |
private S4(): string { | |
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment