All files / platform/core/src/utils addAccessors.js

9.09% Statements 2/22
0% Branches 0/14
0% Functions 0/3
9.09% Lines 2/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 6734x                                                                                             34x                                      
const handler = {
  /**
   * Get a proxied value from the array or property value
   * Note that the property value get works even if you update the underlying object.
   * Also, return true of proxy.__isProxy in order to distinguish proxies and not double proxy them.
   */
  get: (target, prop) => {
    Iif (prop == '__isProxy') {
      return true;
    }
    Iif (prop in target) {
      return target[prop];
    }
    return target[0][prop];
  },
 
  set: (obj, prop, value) => {
    if (typeof prop === 'number' || prop in obj) {
      obj[prop] = value;
    } else {
      obj[0][prop] = value;
    }
    return true;
  },
};
 
/**
 * Add a proxy object for sqZero or the src[0] element if sqZero is unspecified, AND
 * src is an array of length 1.
 *
 * If sqZero isn't passed in, then assume this is a create call on the destination object
 * itself, by:
 * 1. If not an object, return dest
 * 2. If an array of length != 1, return dest
 * 3. If an array, use dest[0] as sqZero
 * 4. Use dest as sqZero
 *
 * @example
 * src = [{a:5,b:'string', c:null}]
 * addAccessors(src)
 * src.c = 'outerChange'
 * src[0].b='innerChange'
 *
 * assert src.a===5
 * assert src[0].c === 'outerChange'
 * assert src.b === 'innerChange'
 */
const addAccessors = (dest, sqZero) => {
  Iif (dest.__isProxy) {
    return dest;
  }
  let itemZero = sqZero;
  Iif (itemZero === undefined) {
    Iif (typeof dest !== 'object') {
      return dest;
    }
    Iif (Array.isArray(dest) && dest.length !== 1) {
      return dest;
    }
    itemZero = Array.isArray(dest) ? dest[0] : dest;
  }
  const ret = [itemZero];
  return new Proxy(ret, handler);
};
 
export default addAccessors;