v1.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.findByPointer = void 0;
  4. const hasOwnProperty_1 = require("@jsonjoy.com/util/lib/hasOwnProperty");
  5. const util_1 = require("../util");
  6. const { isArray } = Array;
  7. const findByPointer = (pointer, val) => {
  8. if (!pointer)
  9. return { val };
  10. let obj;
  11. let key;
  12. let indexOfSlash = 0;
  13. let indexAfterSlash = 1;
  14. while (indexOfSlash > -1) {
  15. indexOfSlash = pointer.indexOf('/', indexAfterSlash);
  16. const component = indexOfSlash > -1 ? pointer.substring(indexAfterSlash, indexOfSlash) : pointer.substring(indexAfterSlash);
  17. indexAfterSlash = indexOfSlash + 1;
  18. key = (0, util_1.unescapeComponent)(component);
  19. obj = val;
  20. if (isArray(obj)) {
  21. if (key === '-')
  22. key = obj.length;
  23. else {
  24. if (!(0, util_1.isValidIndex)(key))
  25. throw new Error('INVALID_INDEX');
  26. key = Number(key);
  27. if (key < 0)
  28. throw new Error('INVALID_INDEX');
  29. }
  30. val = (0, hasOwnProperty_1.hasOwnProperty)(obj, String(key)) ? obj[key] : undefined;
  31. }
  32. else if (typeof obj === 'object' && !!obj) {
  33. val = (0, hasOwnProperty_1.hasOwnProperty)(obj, String(key)) ? obj[key] : undefined;
  34. }
  35. else
  36. throw new Error('NOT_FOUND');
  37. }
  38. return { val, obj, key };
  39. };
  40. exports.findByPointer = findByPointer;