v4.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839
  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 (!isValidIndex(key)) throw new Error('INVALID_INDEX');
  25. key = ~~key;
  26. if (key < 0)
  27. throw new Error('INVALID_INDEX');
  28. }
  29. val = (0, hasOwnProperty_1.hasOwnProperty)(obj, key) ? obj[~~key] : undefined;
  30. }
  31. else if (typeof obj === 'object' && !!obj) {
  32. val = (0, hasOwnProperty_1.hasOwnProperty)(obj, key) ? obj[key] : undefined;
  33. }
  34. else
  35. throw new Error('NOT_FOUND');
  36. }
  37. return { val, obj, key };
  38. };
  39. exports.findByPointer = findByPointer;