function createComparisonFunction(propertyName) {
return function(object1,object2) {
var value1 = object1[propertyName];
var value2 = object2[propertyName];
if(value1 < value2) {
return -1;
} else if(value1 > value2) {
return 1;
} else {
return 0;
}
}
};
这是红宝书中一个知识点,这段代码不是太明白
This is a tool function made for comparing specific data structures. For example, the data structure format is:
At this time, the general
sort
method needs to be written like this, in the form:Problems with this code:
The
value
parameter is hard-coded and must be recoded when sorting other fields.The logic of returning 1 / -1 is redundant and boring.
Directly writing an anonymous function for sorting was not readable enough in the era of the Little Red Book (now that there are arrow functions, it is actually not a big problem).
So for the above case, the author of Red Book designed a general tool function to generate a function [for sorting specific fields]. Note that when you call this utility function, what is returned is a new function, not the sorted result (the so-called higher-order function).
After applying this package, the code looks like:
This simplifies business logic.
What I don’t understand is that it compares the size of a certain attribute of two objects
createComparisonFunction("test")({'test': 1}, {"test": 2})
returns -1
When calling a function, look at it in two steps. First pass in the compared field through
createComparisonFunction()
. Within thecreateComparisonFunction()
function, return an anonymous function. At the same time, since the anonymous function is insidecreateComparisonFunction()
, the parameterpropertyName
that you pass intocreateComparisonFunction()
is also valid for the anonymous function.Through the previous step, the anonymous function you have obtained contains
propertyName
. At this time, you can pass in the two objects you want to compare, compare theirpropertyName
properties within the function, and return the comparison result.This is called a higher-order function.