Skip to content

Instantly share code, notes, and snippets.

@sethdavis512
Created February 28, 2020 02:12
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 sethdavis512/1ca5f236536530c117ec2fed795adb0b to your computer and use it in GitHub Desktop.
Save sethdavis512/1ca5f236536530c117ec2fed795adb0b to your computer and use it in GitHub Desktop.
const itemList = [
{ type: 'TRIANGLE', color: 'RED' },
{ type: 'TRIANGLE', color: 'BLUE' },
{ type: 'SQUARE', color: 'GREEN' },
];
const bucketList = [
{
name: 'TRIANGLES',
condition: (i) => i.type === 'TRIANGLE'
}
]
const distribute = (items, buckets = []) => {
return items.reduce((sorted, currentItem) => {
if (!sorted['UNSORTED']) {
sorted['UNSORTED'] = [];
}
for (let i = 0; i < buckets.length; i++) {
const bucketName = buckets[i].name;
const bucketExists = Array.isArray(sorted[bucketName]);
const passesCondition = buckets[i].condition(currentItem);
if (!bucketExists && bucketName && passesCondition) {
sorted[bucketName] = [currentItem];
break;
} else if (bucketExists && passesCondition) {
sorted[bucketName].push(currentItem);
break;
} else {
sorted['UNSORTED'].push(currentItem);
break;
}
}
return sorted;
}, {});
}
const distributed = distribute(itemList, bucketList);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment