index.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. 'use strict';
  2. const isObject = value => typeof value === 'object' && value !== null;
  3. // Customized for this use-case
  4. const isObjectCustom = value =>
  5. isObject(value) &&
  6. !(value instanceof RegExp) &&
  7. !(value instanceof Error) &&
  8. !(value instanceof Date);
  9. const mapObject = (object, mapper, options, isSeen = new WeakMap()) => {
  10. options = {
  11. deep: false,
  12. target: {},
  13. ...options
  14. };
  15. if (isSeen.has(object)) {
  16. return isSeen.get(object);
  17. }
  18. isSeen.set(object, options.target);
  19. const {target} = options;
  20. delete options.target;
  21. const mapArray = array => array.map(element => isObjectCustom(element) ? mapObject(element, mapper, options, isSeen) : element);
  22. if (Array.isArray(object)) {
  23. return mapArray(object);
  24. }
  25. for (const [key, value] of Object.entries(object)) {
  26. let [newKey, newValue] = mapper(key, value, object);
  27. if (options.deep && isObjectCustom(newValue)) {
  28. newValue = Array.isArray(newValue) ?
  29. mapArray(newValue) :
  30. mapObject(newValue, mapper, options, isSeen);
  31. }
  32. target[newKey] = newValue;
  33. }
  34. return target;
  35. };
  36. module.exports = (object, mapper, options) => {
  37. if (!isObject(object)) {
  38. throw new TypeError(`Expected an object, got \`${object}\` (${typeof object})`);
  39. }
  40. return mapObject(object, mapper, options);
  41. };