UNPKG

@what-a-faka/obj-mutation

Version:

The Object Mutation

82 lines (81 loc) 3.02 kB
"use strict"; // Import here Polyfills if needed. Recommended core-js (npm i -D core-js) // import "core-js/fn/array.find" // ... Object.defineProperty(exports, "__esModule", { value: true }); var defaultOptions = { clean: true, cleanValue: '_falsy', omit: [], }; var ObjMutation = /** @class */ (function () { function ObjMutation(_schema, _options) { if (_schema === void 0) { _schema = {}; } if (_options === void 0) { _options = {}; } this._schema = _schema; this._options = _options; this.schema = _schema; this.options = Object.assign({}, defaultOptions, _options); } ObjMutation.prototype.parse = function (originObj) { var _this = this; if (!originObj) return {}; var newObj = Object.assign({}, originObj); var originObjKeys = Object.keys(this.schema); originObjKeys.forEach(function (originObjKey) { var _a = _this.schema[originObjKey], format = _a.format, mutate = _a.mutate, create = _a.create; var originValue = originObj[originObjKey]; if (!create && !newObj.hasOwnProperty(originObjKey)) return; if (mutate) { delete newObj[originObjKey]; Object.keys(mutate).forEach(function (mutateKey) { newObj[mutateKey] = mutate[mutateKey](originValue); }); return; } else if (create) { newObj[originObjKey] = create(originObj); return; } else if (format) { newObj[originObjKey] = format(originValue); } newObj[originObjKey] = format ? format(originValue) : originValue; }); this.options.omit.forEach(function (key) { delete newObj[key]; }); return this.pipe(newObj); }; ObjMutation.prototype.pipe = function (params) { var _this = this; var piplineFuncs = ['clean'].filter(function (p) { return _this.options[p]; }); var prettyParams = piplineFuncs.reduce(function (result, nextPip) { if (_this.options[nextPip] && _this[nextPip]) { return _this[nextPip](result); } return result; }, params); return Object.keys(prettyParams).length ? prettyParams : {}; }; ObjMutation.prototype.clean = function (params) { var _this = this; var niceParams = {}; Object.keys(params).forEach(function (key) { var isTruth = _this.options.cleanValue === '_falsy' ? false : true; if (isTruth) { if (params[key] !== _this.options.cleanValue) { niceParams[key] = params[key]; } } else if (params[key]) { niceParams[key] = params[key]; } }); return niceParams; }; return ObjMutation; }()); exports.default = ObjMutation;