v5.js 1.4 KB

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