Reputation: 1280
I will use the example from the MDN Array.prototype.filter() docs.
we can pass decoupled functions into higher order functions like this:
function isBigEnough(value) {
return value >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]
Using the example above as reference, is it possible to filter results which are not 'big enough' without defining another decoupled function isSmallEnough()
? In order words, We would like to return [5, 8]
.
Can we reuse isBigEnough
to achieve this?
Upvotes: 0
Views: 2687
Reputation: 1401
Can we reuse
isBigEnough
to achieve this?
Yes, by slightly modifying your code we can even use the same filter method to return just the false values.
function isBigEnough(value) {
return value >= 10;
}
var filterFalse = [12, 5, 8, 130, 44].filter(x => !isBigEnough(x));
// filterFalse - [5, 8]
Upvotes: 0
Reputation: 386746
You could use a wrapper for a not function.
function isBigEnough(value) {
return value >= 10;
}
var not = fn => (...args) => !fn(...args),
filtered = [12, 5, 8, 130, 44].filter(not(isBigEnough));
console.log(filtered);
Upvotes: 0
Reputation: 33496
You can create a function which returns the inverted form of a function:
function not(predicate) {
return function() {
return !predicate.apply(this, arguments);
};
}
function isBigEnough(value) {
return value >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(not(isBigEnough));
console.log(filtered);
Upvotes: 2
Reputation: 22014
Although the existing answers are correct, here's a slightly different take:
let not = x => !x;
let greaterThan = R.curryN(2, (x, y) => y > x);
let greaterThan10 = greaterThan(10); // === isBigEnough
let notGreaterThan10 = R.pipe(greaterThan10, not);
let items = list.filter(notGreaterThan10);
Uses the ramda.js library for composition and currying.
Upvotes: 0
Reputation: 192507
Negate the predicate:
function isBigEnough(value) {
return value >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(function(value) {
return !isBigEnough(value);
});
console.log(filtered);
Upvotes: 1