Consolidate invert modules.

This commit is contained in:
John-David Dalton
2017-01-11 10:39:30 -08:00
parent dcded33f58
commit 36927bff8b
4 changed files with 21 additions and 49 deletions

View File

@@ -1,21 +0,0 @@
import baseForOwn from './baseForOwn.js';
/**
* The base implementation of `invert` and `invertBy` which inverts
* `object` with values transformed by `iteratee` and set by `setter`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} setter The function to set `accumulator` values.
* @param {Function} iteratee The iteratee to transform values.
* @param {Object} accumulator The initial inverted object.
* @returns {Function} Returns `accumulator`.
*/
function baseInverter(object, setter, iteratee, accumulator) {
baseForOwn(object, (value, key, object) => {
setter(accumulator, iteratee(value), key, object);
});
return accumulator;
}
export default baseInverter;

View File

@@ -1,14 +0,0 @@
import baseInverter from './.internal/baseInverter.js';
/**
* Creates a function like `invertBy`.
*
* @private
* @param {Function} setter The function to set accumulator values.
* @returns {Function} Returns the new inverter function.
*/
function createInverter(setter) {
return (object, iteratee) => baseInverter(object, setter, iteratee, {});
}
export default createInverter;

View File

@@ -1,6 +1,4 @@
import constant from './constant.js';
import createInverter from './.internal/createInverter.js';
import identity from './identity.js';
import baseForOwn from './baseForOwn.js';
/**
* Creates an object composed of the inverted keys and values of `object`.
@@ -18,8 +16,12 @@ import identity from './identity.js';
* invert(object);
* // => { '1': 'c', '2': 'b' }
*/
const invert = createInverter((result, value, key) => {
result[value] = key;
});
function invert(object) {
const result = {};
baseForOwn(object, (value, key) => {
result[value] = key;
});
return result;
}
export default invert;

View File

@@ -1,4 +1,4 @@
import createInverter from './.internal/createInverter.js';
import baseForOwn from './baseForOwn.js';
/** Used to check objects for own properties. */
const hasOwnProperty = Object.prototype.hasOwnProperty;
@@ -22,12 +22,17 @@ const hasOwnProperty = Object.prototype.hasOwnProperty;
* invertBy(object, value => `group${ value }`);
* // => { 'group1': ['a', 'c'], 'group2': ['b'] }
*/
const invertBy = createInverter((result, value, key) => {
if (hasOwnProperty.call(result, value)) {
result[value].push(key);
} else {
result[value] = [key];
}
});
function invertBy(object, iteratee) {
const result = {};
baseForOwn(object, (value, key) => {
value = iteratee(value);
if (hasOwnProperty.call(result, value)) {
result[value].push(key);
} else {
result[value] = [key];
}
});
return result;
}
export default invertBy;