Skip to content

Instantly share code, notes, and snippets.

@nullhook
Last active February 18, 2019 09:46
Embed
What would you like to do?
How to filter data using JavaScript
const data = [
{ location: { title: 'b' }, size: 25, price: 830 },
{ location: { title: 'c' }, size: 28, price: 700 },
{ location: { title: 'other' }, size: 21, price: 500 }
];
function main() {
const locationFilter = ['b', 'c'];
const priceFilter = [];
const match = pipe(
filter(x => isEmpty(locationFilter) || locationFilter.includes(x.location.title)),
filter(x => isEmpty(priceFilter) || priceFilter.includes(x.price)),
range('size', 0, 100)
);
return match(data);
}
const includes = item => xs => xs.includes(item);
const filter = f => xs => xs.filter(f);
const range = (key, min, max) => filter(x => x[key] >= min && x[key] <= max);
const isEmpty = arr => arr.length === 0 ? true : false;
// Utilize the previous pipe function that accepts only two functions
const _pipe = (a, b) => (arg) => {
return b(a(arg));
}
// The rest parameters creates an array of operations
const pipe = (...ops) => {
// Iterate over the array of operations
// By using reduce, merge all operations into a single bundle
let bundle = ops.reduce((prevOp, nextOp) => {
return _pipe(prevOp,nextOp);
});
return bundle;
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment