Skip to content

Commit c4c45b0

Browse files
committed
feat(services): uid service
1 parent 1733617 commit c4c45b0

File tree

3 files changed

+41
-0
lines changed

3 files changed

+41
-0
lines changed

projects/coreui-angular/src/lib/services/public_api.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,4 @@ export { ClassToggleService } from './class-toggle.service';
44
export { LocalStorageService } from './local-storage.service';
55
export { InMemoryStorageService } from './in-memory-storage.service';
66
export { ColorModeService, ColorMode } from './color-mode.service';
7+
export { UIDService } from './uid.service';
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import { TestBed } from '@angular/core/testing';
2+
3+
import { UIDService } from './uid.service';
4+
5+
describe('UIDService', () => {
6+
let service: UIDService;
7+
8+
beforeEach(() => {
9+
TestBed.configureTestingModule({});
10+
service = TestBed.inject(UIDService);
11+
});
12+
13+
it('should be created', () => {
14+
expect(service).toBeTruthy();
15+
});
16+
17+
it('should return an UID string', () => {
18+
expect(typeof service.getUID('test')).toBe('string');
19+
expect(service.getUID('test')).toContain('test-');
20+
expect(service.getUID()).toContain('random-id-');
21+
});
22+
});
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import { inject, Injectable } from '@angular/core';
2+
import { DOCUMENT } from '@angular/common';
3+
4+
@Injectable({
5+
providedIn: 'root'
6+
})
7+
export class UIDService {
8+
readonly #document = inject(DOCUMENT);
9+
10+
getUID(prefix: string = 'random-id'): string {
11+
let uid = prefix;
12+
do {
13+
uid = `${prefix}-${Math.floor(Math.random() * 1000000).toString(10)}`;
14+
} while (this.#document.getElementById(uid));
15+
16+
return uid;
17+
}
18+
}

0 commit comments

Comments
 (0)