parse-js
Version:
Utility library for object structure conversion.
44 lines (33 loc) • 1.22 kB
JavaScript
;
var _transform = require('../lib/transform');
var _isArray = require('lodash/isArray');
function MapTransformer(callback, parse) {
if (!(this instanceof MapTransformer)) {
return this.transform(new MapTransformer(callback, this.constructor));
}
this._parse = parse || require('../index');
this._callback = callback;
this._cache = {};
}
MapTransformer.prototype._createParse = function (key) {
var parse = this._parse;
var cache = this._cache;
if (!(key in cache)) cache[key] = this._callback(parse());
return cache[key];
};
MapTransformer.prototype.parse = function (source, instance, root) {
var _this = this;
var accumulator = _isArray(source) ? [] : {};
return _transform(source, function (result, value, key) {
result[key] = _this._createParse(key).parse(value, instance, root);
}, accumulator);
};
MapTransformer.prototype.reverse = function (source, instance, root) {
var _this2 = this;
var isArray = _isArray(source);
var accumulator = isArray ? [] : {};
return _transform(source, function (result, value, key) {
result[key] = _this2._createParse(key).reverse(value, instance, root);
}, accumulator);
};
module.exports = MapTransformer;