deep-map
Version:
Transforms nested values of complex objects
57 lines • 1.94 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var WeakMap = require("es6-weak-map");
var lodash_1 = require("lodash");
exports.deepMapModule = function deepMap(object, mapFn, options) {
options = lodash_1.isNil(options) ? {} : options;
if (!mapFn) {
throw new Error('mapFn is required');
}
else if (!lodash_1.isFunction(mapFn)) {
throw new TypeError('mapFn must be a function');
}
else if (!lodash_1.isObject(options)) {
throw new TypeError('options must be an object');
}
return new DeepMap(mapFn, options).map(object);
};
exports.deepMapModule.default = exports.deepMapModule;
var DeepMap = /** @class */ (function () {
function DeepMap(mapFn, opts) {
this.mapFn = mapFn;
this.opts = opts;
this.cache = new WeakMap();
}
DeepMap.prototype.map = function (value, key) {
return lodash_1.isArray(value) ? this.mapArray(value) :
lodash_1.isObject(value) ? this.mapObject(value) :
this.mapFn.call(this.opts.thisArg, value, key);
};
DeepMap.prototype.mapArray = function (arr) {
if (this.cache.has(arr)) {
return this.cache.get(arr);
}
var length = arr.length;
var result = this.opts.inPlace ? arr : [];
this.cache.set(arr, result);
for (var i = 0; i < length; i++) {
result[i] = this.map(arr[i], i);
}
return result;
};
DeepMap.prototype.mapObject = function (obj) {
if (this.cache.has(obj)) {
return this.cache.get(obj);
}
var result = this.opts.inPlace ? obj : {};
this.cache.set(obj, result);
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
result[key] = this.map(obj[key], key);
}
}
return result;
};
return DeepMap;
}());
//# sourceMappingURL=deep-map.js.map