Fyxerz
Fyxerz

Reputation: 169

Passing a function as argument which uses the argument of parent function but also has it's own argument

I just started playing around with functional programming and am trying to pass a function as an argument of another function. However the function that I am trying to pass also has arguments like so:

function splitStringBy(string, type, func) {

    // Split string by type.
    var splitArray = string.split(type);
    console.log(splitArray);

    // Do something with the array.
    func !== undefined ? func(splitArray) : null;
}



function loopArray(array, func) {

    // Loop through array.
    for (var i = 0; i < array.length; i++) {
        func(array[i]);
    }
}

I need to pass splitArray to my loopArray()

Here's how I'm trying to call it:

splitStringBy($scope.textSpace, "<br>", loopArray(splitArray, function() {
            console.log('It worked!');
}));

Console comes up with Error: splitArray is not defined.

Upvotes: 0

Views: 52

Answers (1)

Evan Geng
Evan Geng

Reputation: 81

Rather than passing loopArray as a function, you're actually calling it, then passing its return value to splitStringBy. Since splitArray isn't defined when you first reference it, it's throwing that error.

What you want to do is something like this:

function splitStringBy(string, type, func) {

    // Split string by type.
    var splitArray = string.split(type);
    console.log(splitArray);

    // Do something with the array.
    func !== undefined ? func(splitArray) : null;
}

function loopArray(func) {
    // Return function for looping.
    return function(array) {
        // Loop through array.
        for (var i = 0; i < array.length; i++) {
            func(array[i]);
        }
    }
}

splitStringBy($scope.textSpace, "<br>", loopArray(function() {
        console.log('It worked!');
}));

This is called currying, where a function passes a function as a return value. loopArray will create a function, then return it. We then pass the newly made function to splitStringBy, which then invokes it.

Upvotes: 1

Related Questions