Naming things
"If you have the name of a spirit, you have power over it." – Gerald Jay Sussman
Can you think of a better name for your exclude
function? I know I can. It's known as notEqual
. Simply knowing it as its true name makes it much more versatile when it comes to problem solving. "exclude" makes sense in the context of filtering an array, but somehow it makes less sense if we wanted to use the exclude
function elsewhere.
if (exclude(a,b))
console.log("a and b are not equal")
Functional programming is all about making functions as reusable as possible, so as we move forward, let's stick with
const notEqual = (x,y) => x !== y
Function.prototype.bind
Function.prototype.bind is used to bind values to function parameters. It's commonly used because it's been native since ECMAScript 5 – meaning you can accomplish your goal without adding any additional dependencies or making any changes to your existing code.
const notEqual = (x,y) => x !== y
const samples = ['foo', 'bar']
const foos = samples.filter(notEqual.bind(null, 'foo'))
console.log(foos) // ["bar"]
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…