Sunday 9 December 2018

JavaScript: Implement map function

Implement a ‘map’ function, that takes a function ‘f’ and an array ‘arr’ as argument, apply function f on every element of array arr.

HelloWorld.js
function map(f, arr){
    var result = [];
    
    for(i in arr){
        result[i] = f(arr[i]);
    }
    
    return result;
}

function printArray(arr){
    for(data of arr){
        console.log(data);
    }
}

function square(num){
    return num * num;    
}

var arr = [1, 2, 3, 4, 5];
var result = map(square, arr);

printArray(result);

Output
1
4
9
16
25



Previous                                                 Next                                                 Home

No comments:

Post a Comment