javascript - Questions about comparison functions
为情所困
为情所困 2017-07-05 11:06:44
0
4
841
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;
        }
    }
};

这是红宝书中一个知识点,这段代码不是太明白
为情所困
为情所困

reply all(4)
过去多啦不再A梦

This is a tool function made for comparing specific data structures. For example, the data structure format is:

let arr = [{ name: 'foo', value: 123 }, { name: 'bar', value: 456 }]

At this time, the general sort method needs to be written like this, in the form:

arr.sort(function (a, b) { return a.value - b.value > 0 ? 1 : -1 })

Problems with this code:

  1. The value parameter is hard-coded and must be recoded when sorting other fields.

  2. The logic of returning 1 / -1 is redundant and boring.

  3. 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:

// 创造一个【根据 value 字段来排序】的函数
let compareFn = createComparisonFunction('value')
// 将创造的函数传入 sort 中作为排序依据
arr.sort(compareFn)

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 the createComparisonFunction() function, return an anonymous function. At the same time, since the anonymous function is inside createComparisonFunction(), the parameter propertyName that you pass into createComparisonFunction() 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 their propertyName properties within the function, and return the comparison result.

我想大声告诉你

This is called a higher-order function.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!