Running nested for loops against array functions in Javascript

I wrote a small block of code yesterday that uses two loops to compare objects in two arrays (the arrays are the same).

var result = []
for (var i = 0; i < res.length; i++) {
    var tempObj = {}
    tempObj.baseName = res[i].name
    tempObj.cnt = res[i].cnt
    tempObj.matches = []
    for (var j = 0; j < compareArr.length; j++) {
        if(natural.LevenshteinDistance(res[i].name, compareArr[j].name) === options.distance) {
            tempObj.matches.push(compareArr[j])
        }
    }
    if (tempObj.matches.length > 0) {
        result.push(tempObj)
    }
}

However, I have been involved in functional programming in the last few months and decided to rewrite the code block using a more functional approach and as a result:

var result = res.
    map(function(baseItem) {
        baseItem.matches = compareArr.
            reduce(function(acc, compItem) {
                if(natural.LevenshteinDistance(baseItem.name, compItem.name) === options.distance) {
                    acc.push(compItem)
                }
                return acc
            }, [])
            return baseItem
        }).
        filter(function(item) {
          return item.matches.length > 0
        })

, , , , , 10 , , . , jsperf, . for 2600 ops/sec, 500 ops/sec.: (

, , ? , ? , javascript **.

? javascript?

** [ amiright?]

http://jhusain.imtqy.com/learnrx/

https://github.com/timoxley/functional-javascript-workshop

https://medium.com/javascript-scene/the-two-pillars-of-javascript-ee6f3281e7f3

, , → http://ejohn.org/blog/partial-functions-in-javascript/

http://shop.oreilly.com/product/0636920028857.do

, , , , .

EDIT: lodash . 870 / 475 /. .

fast.js for js native function , .

+4
1

, , 1) 2) (.map, .reduce) ( , GarbageCollection ). , , .

, , , , . - LevenshteinDistance, .

, , : , options.distance, , , :

for (var j = 0; j < compareArr.length; j++) {
    // This check was added
    if (Math.abs(res[i].name.length - compareArr[j].name.length) > options.distance) {
        continue;
    }
    if(natural.LevenshteinDistance(res[i].name, compareArr[j].name) === options.distance) {
        tempObj.matches.push(compareArr[j])
    }
}

, stackoverflow: fooobar.com/questions/146069/...

0

All Articles