Created
July 1, 2017 14:13
-
-
Save sallar/1233c538e073d96f605d7251564c8d15 to your computer and use it in GitHub Desktop.
Recursive Collection Utils
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
👏