export const LOCAL_STORAGE_KEY = "dx-sidebar-recent-searches"; export const LIMIT = 5; export class RecentSearches { items: string[] = []; constructor() { this._init(); } get() { return this.items; } add(item: string | undefined) { if (!item || typeof item !== "string") { return; } const normalized = item.trim(); if (normalized === "") { return; } this._prepend(normalized); this._removeDuplicates(normalized); this._cutOffExcess(); this._addToStorage(); } // private _init() { this.items = JSON.parse( window.localStorage.getItem(LOCAL_STORAGE_KEY) || "[]" ); } _prepend(item: string) { this.items.unshift(item); } _removeDuplicates(item: string) { while (this.items.lastIndexOf(item) > 0) { this.items.splice(this.items.lastIndexOf(item), 1); } } _cutOffExcess() { this.items = this.items.slice(0, LIMIT); } _addToStorage() { window.localStorage.setItem( LOCAL_STORAGE_KEY, JSON.stringify(this.items) ); } }