running-tools

A collection of tools for runners and their coaches
git clone https://git.ashermorgan.net/running-tools/
Log | Files | Refs | README

utils.ts (1542B)


      1 /*
      2  * Contains utility functions for handling nested objects and interacting with localStorage
      3  */
      4 
      5 // The global localStorage prefix
      6 const LocalStoragePrefix = 'running-tools';
      7 
      8 /**
      9  * Create a deep copy of an object
     10  * @param {Type} value The object to copy
     11  * @returns {Type} The copied object
     12  */
     13 export function deepCopy<Type>(value: Type): Type {
     14   return JSON.parse(JSON.stringify(value));
     15 }
     16 
     17 /**
     18  * Test whether two objects are deeply equal
     19  * @param {Type} value1 The first object
     20  * @param {Type} value2 The second object
     21  * @returns {boolean} Whether the two objects are equal
     22  */
     23 export function deepEqual<Type>(value1: Type, value2: Type): boolean {
     24   return JSON.stringify(value1) === JSON.stringify(value2);
     25 }
     26 
     27 /**
     28  * Read an object from a localStorage item
     29  * @param {string} key The localStorage item's key
     30  * @returns {Type} The object
     31  */
     32 export function getLocalStorage<Type>(key: string): Type | null {
     33   try {
     34     return JSON.parse(localStorage.getItem(`${LocalStoragePrefix}.${key}`) || '');
     35   } catch {
     36     return null;
     37   }
     38 }
     39 
     40 /**
     41  * Write an object to a localStorage item
     42  * @param {string} key The localStorage item's key
     43  * @param {Type} value The object to write
     44  */
     45 export function setLocalStorage<Type>(key: string, value: Type) {
     46   localStorage.setItem(`${LocalStoragePrefix}.${key}`, JSON.stringify(value));
     47 }
     48 
     49 /**
     50  * Delete a localStorage item
     51  * @param {string} key The localStorage item's key
     52  */
     53 export function unsetLocalStorage(key: string) {
     54   localStorage.removeItem(`${LocalStoragePrefix}.${key}`);
     55 }