_optionalChain.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. Object.defineProperty(exports, '__esModule', { value: true });
  2. /**
  3. * Polyfill for the optional chain operator, `?.`, given previous conversion of the expression into an array of values,
  4. * descriptors, and functions.
  5. *
  6. * Adapted from Sucrase (https://github.com/alangpierce/sucrase)
  7. * See https://github.com/alangpierce/sucrase/blob/265887868966917f3b924ce38dfad01fbab1329f/src/transformers/OptionalChainingNullishTransformer.ts#L15
  8. *
  9. * @param ops Array result of expression conversion
  10. * @returns The value of the expression
  11. */
  12. function _optionalChain(ops) {
  13. let lastAccessLHS = undefined;
  14. let value = ops[0];
  15. let i = 1;
  16. while (i < ops.length) {
  17. const op = ops[i] ;
  18. const fn = ops[i + 1] ;
  19. i += 2;
  20. // by checking for loose equality to `null`, we catch both `null` and `undefined`
  21. if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) {
  22. // really we're meaning to return `undefined` as an actual value here, but it saves bytes not to write it
  23. return;
  24. }
  25. if (op === 'access' || op === 'optionalAccess') {
  26. lastAccessLHS = value;
  27. value = fn(value);
  28. } else if (op === 'call' || op === 'optionalCall') {
  29. value = fn((...args) => (value ).call(lastAccessLHS, ...args));
  30. lastAccessLHS = undefined;
  31. }
  32. }
  33. return value;
  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. exports._optionalChain = _optionalChain;
  58. //# sourceMappingURL=_optionalChain.js.map