Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

commented Jul 17, 2017

👏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.