utils.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. 'use strict';
  2. const Reach = require('./reach');
  3. const internals = {};
  4. exports.keys = function (obj, options = {}) {
  5. return options.symbols !== false ? Reflect.ownKeys(obj) : Object.getOwnPropertyNames(obj); // Defaults to true
  6. };
  7. exports.store = function (source, keys) {
  8. const storage = new Map();
  9. for (let i = 0; i < keys.length; ++i) {
  10. const key = keys[i];
  11. const value = Reach(source, key);
  12. if (typeof value === 'object' ||
  13. typeof value === 'function') {
  14. storage.set(key, value);
  15. internals.reachSet(source, key, undefined);
  16. }
  17. }
  18. return storage;
  19. };
  20. exports.restore = function (copy, source, storage) {
  21. for (const [key, value] of storage) {
  22. internals.reachSet(copy, key, value);
  23. internals.reachSet(source, key, value);
  24. }
  25. };
  26. internals.reachSet = function (obj, key, value) {
  27. const path = Array.isArray(key) ? key : key.split('.');
  28. let ref = obj;
  29. for (let i = 0; i < path.length; ++i) {
  30. const segment = path[i];
  31. if (i + 1 === path.length) {
  32. ref[segment] = value;
  33. }
  34. ref = ref[segment];
  35. }
  36. };