Praktikum_mf

set

Mar 30th, 2021 (edited)
292
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. type Indexed<T = any> = {
  2.     [key in string]: T;
  3. };
  4.  
  5. function merge(lhs: Indexed, rhs: Indexed): Indexed {
  6.     for (let p in rhs) {
  7.         if (!rhs.hasOwnProperty(p)) {
  8.             continue;
  9.         }
  10.  
  11.         try {
  12.             if (rhs[p].constructor === Object) {
  13.                 rhs[p] = merge(lhs[p] as Indexed, rhs[p] as Indexed);
  14.             } else {
  15.                 lhs[p] = rhs[p];
  16.             }
  17.         } catch(e) {
  18.             lhs[p] = rhs[p];
  19.         }
  20.     }
  21.  
  22.     return lhs;
  23. }
  24.  
  25. function set(object: Indexed | unknown, path: string, value: unknown): Indexed | unknown {
  26.     if (typeof object !== 'object') {
  27.         return object;
  28.     }
  29.  
  30.     if (typeof path !== 'string') {
  31.         throw new Error('path must be string');
  32.     }
  33.  
  34.     const result = path.split('.').reduceRight<Indexed>((acc, key) => ({
  35.         [key]: acc,
  36.     }), value as any);
  37.     return merge(object as Indexed, result);
  38. }
  39.  
  40. export default set
Add Comment
Please, Sign In to add comment