Created
May 3, 2020 11:31
-
-
Save armanozak/2477e38f55995c52f3b159db9521bfcb to your computer and use it in GitHub Desktop.
[Strategy Pattern with TypeScript - ABP Angular Implementation] DomInsertionService #blog #typescript
This file contains hidden or 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'; | |
import { ContentStrategy } from '../strategies/content.strategy'; | |
import { generateHash } from '../utils'; | |
@Injectable({ providedIn: 'root' }) | |
export class DomInsertionService { | |
private readonly inserted = new Set<number>(); | |
insertContent<T extends HTMLScriptElement | HTMLStyleElement>( | |
contentStrategy: ContentStrategy<T>, | |
): T { | |
const hash = generateHash(contentStrategy.content); | |
if (this.inserted.has(hash)) return; | |
const element = contentStrategy.insertElement(); | |
this.inserted.add(hash); | |
return element; | |
} | |
removeContent(element: HTMLScriptElement | HTMLStyleElement) { | |
const hash = generateHash(element.textContent); | |
this.inserted.delete(hash); | |
element.parentNode.removeChild(element); | |
} | |
has(content: string): boolean { | |
const hash = generateHash(content); | |
return this.inserted.has(hash); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment