UNPKG

shapey

Version:

A simple syntax for remapping objects, inspired by several of Ramda's spec based functions

61 lines (48 loc) 2.63 kB
"use strict"; exports.__esModule = true; exports.default = void 0; var _curryN = _interopRequireDefault(require("vanillas/curryN")); var _curry = _interopRequireDefault(require("vanillas/curry")); var _isObject = _interopRequireDefault(require("vanillas/isObject")); var _has = _interopRequireDefault(require("vanillas/has")); var _map = _interopRequireDefault(require("vanillas/map")); var _util = require("./util"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var makeSpec = function makeSpec(transforms) { var spec = (0, _map.default)(function (v) { return (0, _isObject.default)(v) ? makeSpec(v) : (0, _util.alwaysFunction)(v); }, (0, _util.safeSpecTransforms)(transforms)); var arity = Math.max.apply(Math, Object.values(spec).filter(function (v) { return (0, _has.default)('length', v); }).map(function (v) { return v.length; }).concat([0])); return (0, _curryN.default)(arity, function () { for (var _len = arguments.length, allArgs = new Array(_len), _key = 0; _key < _len; _key++) { allArgs[_key] = arguments[_key]; } return (0, _map.default)(function (fn) { return fn.apply(void 0, allArgs); }, spec); }); }; /** * A port over of [Ramda's applySpec()](http://ramdajs.com/docs/#applySpec), but with a few changes you may or may not see as necessary. * (1) Properly curried so that you can optionally provide args as (spec, input) rather than only as (spec)(input) * (2) It wraps each function in a tryCatch that logs the key name of the transform function that fails. * * Using applySpec() in the wild and at-scale proved to be one of the hardest Ramda functions to debug. * Limiting its functionality and adding console logging doesn't sound like a necessary thing, but when working with Ramda on a full team it may help prevent devs from getting so frustrated that they vote to abandon the library while they're still learning the functional programming paradigm. * * @function * @name mapSpec * @sig {k: v} -> {k: v} -> {k: v} * @param {Object} spec An object whose values are functions which expect the entire object to be fed in as input. This is identical to the input you'd pass into applySpec() * @param {Object} input An object to be mapped over (transformed) * @returns {Object} The input object transformed to contain only the props named in the spec (with the corresponding transforms applied at that key) */ var _default = (0, _curry.default)(function (transforms, input) { return makeSpec(transforms)(input); }); exports.default = _default; module.exports = exports.default;