Created
February 28, 2020 02:12
-
-
Save sethdavis512/1ca5f236536530c117ec2fed795adb0b to your computer and use it in GitHub Desktop.
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
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