v6.js 1.3 KB

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