Skip to content

Commit

Permalink
refactor: groupedByOne and groupedByMany refactored
Browse files Browse the repository at this point in the history
Both functions have been refactored to reflect the changes introduced on sveltin v.0.6.0 with page endpoints
  • Loading branch information
indaco committed Mar 12, 2022
1 parent 9cda37b commit 5684da1
Showing 1 changed file with 29 additions and 27 deletions.
56 changes: 29 additions & 27 deletions src/lib/utils/collections.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,17 @@ import reduce from 'lodash-es/reduce.js';

/**
* @param {string} on
* @param {any[]} collection
* @param {string[]} giveBack
* @param {Array.<Object>} collection
* @param {Array.<string>} giveBack
*
* @returns {Array.<Object>}
*/
export const groupedByOne = (on, collection, giveBack) => {
const res = [];
const obj = {};

forEach(collection, (curr) => {
const property = curr[on];
const property = curr.meta[on];
if (property != undefined) {
if (!(property in obj)) {
obj[property] = { name: property, items: [] };
Expand All @@ -20,7 +22,7 @@ export const groupedByOne = (on, collection, giveBack) => {

let result = {};
forEach(giveBack, (value) => {
result[value] = curr[value];
result[value] = curr.meta[value];
});
obj[property].items.push(result);
}
Expand All @@ -31,30 +33,30 @@ export const groupedByOne = (on, collection, giveBack) => {

/**
* @param {string} on
* @param {any[]} collection
* @param {string[]} giveBack
* @param {Array.<Object>} collection
* @param {Array.<string>} giveBack
*
* @returns {Array.<Object>}
*/
export const groupedByMany = (on, collection, giveBack) => {
return [
Object.entries(
reduce(
collection,
(acc, curr) => {
forEach(curr[on], function (item) {
let result = {};
forEach(giveBack, (element) => {
result[element] = curr[element];
});
if (acc[item]) {
acc[item].push(result);
} else {
acc[item] = [result];
}
return Object.entries(
reduce(
collection,
(acc, curr) => {
forEach(curr.meta[on], function (item) {
let result = {};
forEach(giveBack, (element) => {
result[element] = curr.meta[element];
});
return acc;
},
{}
)
).map(([name, items]) => ({ name, items }))
];
if (acc[item]) {
acc[item].push(result);
} else {
acc[item] = [result];
}
});
return acc;
},
{}
)
).map(([name, items]) => ({ name, items }));
};

0 comments on commit 5684da1

Please sign in to comment.