Skip to content

Instantly share code, notes, and snippets.

@vinzdef
Last active August 31, 2018 16:44
Show Gist options
  • Save vinzdef/1e44b27a6f71955947aedf9604f874ad to your computer and use it in GitHub Desktop.
Save vinzdef/1e44b27a6f71955947aedf9604f874ad to your computer and use it in GitHub Desktop.
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