UNPKG

mappet

Version:

Lightweight, composable mappers for object transformations

46 lines 1.76 kB
"use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; Object.defineProperty(exports, "__esModule", { value: true }); var get = require("lodash/get"); function identity(val) { return val; } function always(_val) { return true; } function isPath(schemaEntry) { return typeof schemaEntry === "string" || Array.isArray(schemaEntry); } function mappet(schema, options) { if (options === void 0) { options = {}; } var strict = options.strict, _a = options.name, name = _a === void 0 ? "Mappet" : _a, greedy = options.greedy; return function (source) { return Object.keys(schema).reduce(function (result, key) { var _a; var schemaEntry = schema[key]; var include = isPath(schemaEntry) ? always : schemaEntry.include || always; var path = isPath(schemaEntry) ? schemaEntry : schemaEntry.path; var value = get(source, path); if (!include(value, source)) { return result; } var modifier = isPath(schemaEntry) ? identity : schemaEntry.modifier || identity; if (strict && value === undefined) { throw new Error(name + ": " + path + " not found"); } return __assign({}, result, (_a = {}, _a[key] = modifier(value, source), _a)); }, greedy ? source : {}); }; } exports.default = mappet; //# sourceMappingURL=mappet.js.map