i'm the very beginner in functional programming and I want to transform the grep function in jquery.
I just want to detect my incorrect point in the code not just answer.

The original grep function is

function grep( elems, callback, invert ) {
        var callbackInverse,
            matches = [],
            i = 0,
            length = elems.length,
            callbackExpect = !invert;

        // Go through the array, only saving the items
        // that pass the validator function
        for ( ; i < length; i++ ) {
            callbackInverse = !callback( elems[ i ], i );
            if ( callbackInverse !== callbackExpect ) {
                matches.push( elems[ i ] );
            }
        }

        return matches;
    }  


grep([1,2,3,4,5], function(k){return k<4}, true); 
 
And my code is

function my_grep(elems, callback, invert) {
  var callbackInverse,
    matches = [],
    i = 0,
    length = elems.length,
    callbackExpect = !invert;

  let fun = 
    matches => {
    let r = R.range(0,length);
    let modify = R.curry(
        p=>{
            let callbackInverse = !callback( elems[ p ], p );
            if ( callbackInverse !== callbackExpect ) {
                matches.push( elems[ p ] );
            }
        }
    );
    R.map(modify,r);
    return matches;
   };

  fun(length); 
}
console.log(
  my_grep([1,2,3,4,5], function(k){return k<4}, true)
)  

Please just point out what I did incorrectly in my code.

For example, in original grep function,

grep([1,2,3,4,5], function(k){return k<4}, true) 

makes output

[4,5]

But my code make error saying

matches.push( elems[ p ] );

TypeError: matches.push is not a function

0 Answers