_optionalChain.js
1 /** 2 * Polyfill for the optional chain operator, `?.`, given previous conversion of the expression into an array of values, 3 * descriptors, and functions. 4 * 5 * Adapted from Sucrase (https://github.com/alangpierce/sucrase) 6 * See https://github.com/alangpierce/sucrase/blob/265887868966917f3b924ce38dfad01fbab1329f/src/transformers/OptionalChainingNullishTransformer.ts#L15 7 * 8 * @param ops Array result of expression conversion 9 * @returns The value of the expression 10 */ 11 function _optionalChain(ops) { 12 let lastAccessLHS = undefined; 13 let value = ops[0]; 14 let i = 1; 15 while (i < ops.length) { 16 const op = ops[i] ; 17 const fn = ops[i + 1] ; 18 i += 2; 19 // by checking for loose equality to `null`, we catch both `null` and `undefined` 20 if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { 21 // really we're meaning to return `undefined` as an actual value here, but it saves bytes not to write it 22 return; 23 } 24 if (op === 'access' || op === 'optionalAccess') { 25 lastAccessLHS = value; 26 value = fn(value); 27 } else if (op === 'call' || op === 'optionalCall') { 28 value = fn((...args) => (value ).call(lastAccessLHS, ...args)); 29 lastAccessLHS = undefined; 30 } 31 } 32 return value; 33 } 34 35 // Sucrase version 36 // function _optionalChain(ops) { 37 // let lastAccessLHS = undefined; 38 // let value = ops[0]; 39 // let i = 1; 40 // while (i < ops.length) { 41 // const op = ops[i]; 42 // const fn = ops[i + 1]; 43 // i += 2; 44 // if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { 45 // return undefined; 46 // } 47 // if (op === 'access' || op === 'optionalAccess') { 48 // lastAccessLHS = value; 49 // value = fn(value); 50 // } else if (op === 'call' || op === 'optionalCall') { 51 // value = fn((...args) => value.call(lastAccessLHS, ...args)); 52 // lastAccessLHS = undefined; 53 // } 54 // } 55 // return value; 56 // } 57 58 export { _optionalChain }; 59 //# sourceMappingURL=_optionalChain.js.map