Search code examples
javascriptarrayslodash

How lodash "_.every" works with an empty predication param?


I want to replace lodash _.every method with the native every from Array.prototype.

I faced with the case when array is checked with the empty predication like this _.every(arr).

What should I place into a native every method to get the same result as in the lodash?


Solution

  • From the documentation, the _.every() function takes the _.identity() as the default predicate.

    So we can substitute the function v => v for this (the identity function simply returns the first argument).

    const testInputs = [[true, false], [true, true], [false, false], [false, true]]
    
    for(let i = 0; i < testInputs.length; i++) {
        console.log(`Test #${i+1}`);
        console.log('_.every():', _.every(testInputs[i]));
        console.log('Array.every():', testInputs[i].every(v => v));
    }
    .as-console-wrapper { max-height: 100% !important; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>