index.js 1.5 KB

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