0

I'm new in Javascript and I'm try to apply a function to each element of an array and then return the output recursively. Can you help me? I have the loop to go thought the element of the array but I don't know the signature to apply to them the function. Here is my part of the code:

function mapReduce(f, a, seed) {
     for(i = 0; i != a.length; i++){

    }
}

Where f is the function, a is the array and seed is a value that I have to add at the end (I have to sum the output and then add the seed parameter). Hope you can help me. Sorry if the question could result stupid

var itemize = function(x) {
    if(x == undefined){
        return undefined
    } else {
    var str = "<li>";
    var fin = "</li>";
    return str + x + fin;
    }
 };

The test is:

equal(mapReduce(itemize, ["A","B","C"]), "<.li>A<./li><.li>B<./li><.li>C<./li>" ,    "MapReduce(itemize, ['A','B','C']) should yield '<.li>A<./li><.li>B<./li><.li>C<./li>'")

For the map reduced I did something like this:

 function mapReduce(f, a, seed) {
 for(i = 0; i != a.length; i++){
    if(seed != undefined){
        if(a != undefined) {
            seed = seed + f(a[i]);
        } else {
            return undefined;
        }
    } else {
        var d = "";
        d = d + f(a[i]);
    }

}
return seed;
}
0

1 Answer 1

1

It seems like you want your mapReduce function to be equivalent to

a.map(f).reduce(function(prev, item) {
    return item == undefined ? prev : prev + item;
}, seed == undefined ? "" : seed)

If you want to combine this behaviour in a dedicated function, remove the intermediate array and make the for-loop explicit you would write

function mapCombineString(f, a, seed) {
    if (!f || !a) return; // throw new TypeError() would be appropriate
    if (seed == undefined)
        seed = "";
    for (var i = 0; i != a.length; i++) {
        var item = f(a[i], i, a);
        if (item != undefined)
            seed = seed + f(a[i]);
    }
    return seed;
}
Sign up to request clarification or add additional context in comments.

1 Comment

it's enough to say "amazing"? Yes it works perfectly. I use a stupid intermediate array. Thanks for all Bergi

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.