Skip to content

Instantly share code, notes, and snippets.

@MrGrigri
Last active July 2, 2019 15:55
Show Gist options
  • Save MrGrigri/7e182fe5ac4f36b47ebc2cd568cc7e33 to your computer and use it in GitHub Desktop.
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.
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