Last active
August 31, 2018 16:44
-
-
Save vinzdef/1e44b27a6f71955947aedf9604f874ad 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 input = [ | |
{ type: 'a', distance: 5 }, | |
{ type: 'c', distance: 3 }, | |
{ type: 'b', distance: 6 }, | |
{ type: 'c', distance: 12 }, | |
{ type: 'b', distance: 1 }, | |
{ type: 'a', distance: 5 }, | |
{ type: 'b', distance: 6 }, | |
{ type: 'a', distance: -1 }, | |
{ type: 'c', distance: 9 }, | |
{ type: 'd', distance: 10 } | |
] | |
// Filtering useless types | |
const filterType = o => o.type !== 'a' | |
// Filtering without distance (for safety) | |
const filterNoDistance = o => o.hasOwnProperty('distance') | |
// Reduce by distance, ignore < 0 and > 10, could be a third filter | |
const reduceDistance = (acc, o) => { | |
if (o.distance < 0 || o.distance > 10) return acc | |
if (o.distance < 4) { | |
acc.near.push(o) | |
} else if (o.distance < 8) { | |
acc.medium.push(o) | |
} else { | |
acc.far.push(o) | |
} | |
return acc | |
} | |
const accumulator = { | |
near: [], | |
medium: [], | |
far: [] | |
} | |
const output = input | |
.filter(filterType) | |
.filter(filterNoDistance) | |
.reduce(reduceDistance, accumulator) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment