Skip to content

Instantly share code, notes, and snippets.

@sallar
Created July 1, 2017 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sallar/1233c538e073d96f605d7251564c8d15 to your computer and use it in GitHub Desktop.
Save sallar/1233c538e073d96f605d7251564c8d15 to your computer and use it in GitHub Desktop.
Recursive Collection Utils
// By Sallar Kaboli
import { sortBy, at } from 'lodash';
export function sortDeepByKey(list, sortKey, childrenKey) {
if (!sortKey || !childrenKey) {
throw new Error('Insufficient data provided for sorting');
}
return sortByKey(list, sortKey).map(item => {
return {
...item,
[childrenKey]: sortDeepByKey(item[childrenKey], sortKey, childrenKey)
};
});
}
export function deepFilter(list, key, fn) {
return list
.filter(fn)
.map(item => ({
...item,
[key]: deepFilter(item[key], key, fn)
}));
}
export function deepMap(list, key, fn) {
return list
.map(fn)
.map(item => ({
...item,
[key]: deepMap(item[key], key, fn)
}));
}
export function deepAdd(list, id, key, newItem) {
if (id === null) {
return [
newItem,
...list
];
}
return list.map(item => {
return {
...item,
[key]: (item.id === id)
? [newItem, ...item[key]]
: deepAdd(item[key], id, key, newItem)
};
});
}
export function deepFindById(list, id, key) {
if (!Array.isArray(list)) {
return null;
}
for (const item of list) {
if (item.id === id) {
return item;
}
const resultInChild = deepFindById(item[key], id, key);
if (resultInChild !== null) {
return resultInChild;
}
}
return null;
}
export function deepFindParentById(list, id, key, currentId = null) {
for (const item of list) {
if (item.id === id) {
return currentId;
}
const findInChildren = deepFindParentById(item[key], id, key, item.id);
if (findInChildren !== false) {
return findInChildren;
}
}
return false;
}
@najibla
Copy link

najibla commented Jul 17, 2017

👏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment