Skip to content

Instantly share code, notes, and snippets.

@evanrs
Last active June 7, 2017 04:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evanrs/b1986bb0b6f3ddd02c47e1aeb5a46f6a to your computer and use it in GitHub Desktop.
Save evanrs/b1986bb0b6f3ddd02c47e1aeb5a46f6a to your computer and use it in GitHub Desktop.
Functions
import flatMap from 'lodash/flatMap';
import keys from 'lodash/keys';
import get from 'lodash/get';
import identity from 'lodash/identity';
import isArray from 'lodash/isArray';
import isDate from 'lodash/isDate';
import isFunction from 'lodash/isFunction';
import isObject from 'lodash/isObject';
import map from 'lodash/map';
import zipObject from 'lodash/zipObject';
/**
* Returns paths of an object such that { a: { b: { c: [1, 2, 3] } } }
* becomes ['a.b.c']
*/
export const flatMapPaths = (
obj,
iteratee=identity,
path=[]
) =>
flatMap(keys(obj), (key, val) => {
val = get(obj, key);
key = [...path, key];
return (
! isObject(val) || isArray(val) || isFunction(val) || isDate(val) ?
iteratee(key.join('.'), val) : flatMapPaths(val, iteratee, key)
)
})
;
/**
* Returns values given by flatMapPaths as an array
*/
export const flatMapValues = (
obj,
iteratee=identity,
paths=flatMapPaths(obj)
) =>
map(paths, (key) => iteratee(get(obj, key), key))
;
/**
* Flattens nested objects such that { a: { b: { c: [1, 2, 3] } } }
* becomes { 'a.b.c': [1, 2, 3] }
*/
export const flatMapObject = (
obj,
iterateeV=identity,
iterateeK=identity,
paths=flatMapPaths(obj, iterateeK)
) =>
zipObject(paths, flatMapValues(obj, iterateeV, paths))
;
import _ from 'lodash'
const interleave = (...args) => {
const weave = [];
const sources = _.filter(args, _.isArray);
const total = _.sumBy(sources, 'length');
for(let i = 0; i < total; i++) {
let index = i % sources.length;
let source = sources[index];
let value;
[value, ...source] = source;
sources[index] = source;
weave.push(value);
}
return weave
}
{
"name": "flatMapObject",
"version": "1.0.0",
"description": "Map object graph",
"main": "flatMapObject.js",
"repository": {
"type": "git",
"url": "git+https://gist.github.com/b1986bb0b6f3ddd02c47e1aeb5a46f6a.git"
},
"keywords": ["lodash", "flatMap", "graph"],
"author": "Evan Schneider",
"license": "ISC",
"bugs": {
"url": "https://gist.github.com/0c30bb9b858e95c32d0e8cc76c7662dd"
},
"dependencies": {
"lodash": "4.*"
},
"homepage": "https://gist.github.com/b1986bb0b6f3ddd02c47e1aeb5a46f6a"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment