Remove lodash chunk, groupBy

(re: #6087)
This commit is contained in:
Bryan Housel
2019-03-27 16:18:41 -04:00
parent 4cc8d796a6
commit 3d80e6505f
15 changed files with 164 additions and 82 deletions
+45
View File
@@ -44,3 +44,48 @@ export function utilArrayUnion(a, b) {
export function utilArrayUniq(a) {
return Array.from(new Set(a));
}
// Splits array into chunks of given chunk size
// var a = [1,2,3,4,5,6,7];
// utilArrayChunk(a, 3);
// [[1,2,3],[4,5,6],[7]];
export function utilArrayChunk(a, chunkSize) {
if (!chunkSize || chunkSize < 0) return [a.slice()];
var result = new Array(Math.ceil(a.length / chunkSize));
return Array.from(result, function(item, i) {
return a.slice(i * chunkSize, i * chunkSize + chunkSize);
});
}
// Groups the items of the Array according to the given key
// `key` can be passed as a property or as a key function
//
// var pets = [
// { type: 'Dog', name: 'Spot' },
// { type: 'Cat', name: 'Tiger' },
// { type: 'Dog', name: 'Rover' },
// { type: 'Cat', name: 'Leo' }
// ];
//
// utilArrayGroupBy(pets, 'type')
// {
// 'Dog': [{type: 'Dog', name: 'Spot'}, {type: 'Dog', name: 'Rover'}],
// 'Cat': [{type: 'Cat', name: 'Tiger'}, {type: 'Cat', name: 'Leo'}]
// }
//
// utilArrayGroupBy(pets, function(item) { return item.name.length; })
// {
// 3: [{type: 'Cat', name: 'Leo'}],
// 4: [{type: 'Dog', name: 'Spot'}],
// 5: [{type: 'Cat', name: 'Tiger'}, {type: 'Dog', name: 'Rover'}]
// }
export function utilArrayGroupBy(a, key) {
return a.reduce(function(acc, item) {
var group = (typeof key === 'function') ? key(item) : item[key];
(acc[group] = acc[group] || []).push(item);
return acc;
}, {});
}