UNPKG

transformer-js

Version:

[![npm version](https://badge.fury.io/js/transformer-js.svg)](https://badge.fury.io/js/transformer-js) [![codecov](https://codecov.io/gh/peterjcaulfield/transformer-js/branch/master/graph/badge.svg)](https://codecov.io/gh/peterjcaulfield/transformer-js) [

89 lines (76 loc) 2.69 kB
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var traverse = require('traverse'); var KEY_MATCH = 'key'; var VALUE_MATCH = 'value'; var test = function test(prop, config, TYPE) { return config.find(function (obj) { var matcher = obj[TYPE]; if (matcher) { if (typeof matcher === 'function') { return matcher(prop); } else if ((typeof matcher === 'undefined' ? 'undefined' : _typeof(matcher)) === 'object') { return matcher.test(prop); } } return false; }); }; var matcher = function matcher(prop, config, TYPE) { var match = test(prop, config.matchers, TYPE); if (match) { return match.transform ? match.transform : config.transform; } }; /** * @typedef matcher * @type Object * @property {Function} [transform] - default transform that is applied to any * value matched unless * @property {(Rejex|Function)} [key] - used to peform matching on keys. * @property {(Rejex|Function)} [value] - used to perform matching on values. */ /** * @typedef transformer * @type Object * @property {Function} map - executes the transformer and returns a new * transformed object */ /** * @function transformerFactory * @param {Object} transformerConfig * @param {Function} transformerConfig.transform - function to compute new * value from any value matched by the matcher. If not defined the default * transform will be used. * @param {Array<matcher>} transformerConfig.matchers - array of matcher objects * @return {transformer} a transformer instance */ var transformerFactory = function transformerFactory(userConfig) { var config = Object.assign({ matchValues: true, matchkeys: true }, userConfig); var matchKeys = config.matchKeys, matchValues = config.matchValues; var map = function map(obj) { return traverse(obj).map(function (val) { var transform = void 0; if (matchKeys === false) { if (!this.isLeaf) return; transform = matcher(val, config, VALUE_MATCH); } else if (matchValues === false) { transform = matcher(this.key, config, KEY_MATCH); } else { transform = matcher(this.key, config, KEY_MATCH) || matcher(val, config, VALUE_MATCH); } if (typeof transform === 'function') { this.update(transform(val)); } }); }; return { map: map }; }; exports.default = transformerFactory;