|
| 1 | +import { Injectable } from '@angular/core'; |
| 2 | + |
| 3 | +@Injectable({ |
| 4 | + providedIn: 'root' |
| 5 | +}) |
| 6 | +export class NgxListManager<T> { |
| 7 | + |
| 8 | + /** |
| 9 | + * A variable that contains the elements of the list. |
| 10 | + */ |
| 11 | + private _list: T[] = []; |
| 12 | + |
| 13 | + /** |
| 14 | + * Returns a boolean value indicating if the item passed exists on the list. |
| 15 | + * @param item A item value. |
| 16 | + * @returns A boolean value.. |
| 17 | + */ |
| 18 | + private exists(item: T): boolean{ |
| 19 | + return this._list.some((e)=>JSON.stringify(e)===JSON.stringify(item)); |
| 20 | + } |
| 21 | + |
| 22 | + /** |
| 23 | + * Insert or remove using the boolean param insert as flag, the passed element will be inserted if insert parameter is true and it does not alredy exist, or deleted if it is false and exists on the list. |
| 24 | + * @param item A item value to insert or remove from the list. |
| 25 | + * @param insert A boolean value. |
| 26 | + */ |
| 27 | + insertOrRemove(item: T, insert: boolean){ |
| 28 | + const exists = this.exists(item); |
| 29 | + if(insert && !exists){ |
| 30 | + this.insert(item); |
| 31 | + }else if(!insert && exists){ |
| 32 | + this.remove(item); |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * Insert a new element into the list if it doesn't already exist. If force parameter is true, the element will be inserted. |
| 38 | + * @param item A item value to insert. |
| 39 | + * @param force A boolean value. (default = false) |
| 40 | + */ |
| 41 | + insert(item: T, force: boolean = false){ |
| 42 | + const exists = this.exists(item); |
| 43 | + if(!exists || force){ |
| 44 | + this._list.push(item); |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + /** |
| 49 | + * Delete an item that match with the passed element. |
| 50 | + * @param item |
| 51 | + */ |
| 52 | + remove(item: T){ |
| 53 | + const exists = this.exists(item); |
| 54 | + if(exists){ |
| 55 | + this._list = this._list.filter((e)=>e!==item); |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + /** |
| 60 | + * Delete an item at passed position. |
| 61 | + * @param item |
| 62 | + */ |
| 63 | + removeIndex(index: number){ |
| 64 | + const exists =this._list[index]; |
| 65 | + if(exists){ |
| 66 | + this._list = this._list.filter((e,i)=>i!==index); |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + /** |
| 71 | + * Assign a complete list. |
| 72 | + * @param list |
| 73 | + */ |
| 74 | + assign(list: T[]){ |
| 75 | + this._list = list; |
| 76 | + } |
| 77 | + |
| 78 | + /** |
| 79 | + * Clear the list. |
| 80 | + */ |
| 81 | + clear(){ |
| 82 | + this._list = []; |
| 83 | + } |
| 84 | + |
| 85 | + /** |
| 86 | + * Return the complete list. |
| 87 | + * @returns List that contains all elements added. |
| 88 | + */ |
| 89 | + list(): T[]{ |
| 90 | + return this._list; |
| 91 | + } |
| 92 | +} |
0 commit comments