Last Updated: February 25, 2016
·
1.554K
· kjellski

MapReduce Example from Coursera Scala translated to JS

/* This function returns a function that has 
 * two parameters. Called, it will call map(x)
 * for each x smaller y and reduce these by the
 * reduce function.
 * 
 * The unit enables you to provide neutral opertaion
 * elements to the function.
 */
function mapReduce(x, y, reduce, map, unit) {
    return function result(x, y) {
        if (x > y) 
            return unit;
        else 
            return reduce( map(x), result((x + 1), y) );
    };
}

function sum(x, y) {
    return mapReduce(x, y, 
        // javascript has no way to access 
        // the '+' as a function
        function plus(x, y) { return x + y; }, 
        function identity(e) { return e; }, 
        0)(x, y);
}

function sumCubes(x, y) {
    return mapReduce(x, y, 
        function plus(x, y) { return x + y; }, 
        function cube(x) { return x * x * x; }, 
        0)(x, y);
}

function product(x, y) {
    return mapReduce(x, y, 
        // same here, no way to access '*' directly
        function plusCubes(x, y) { return x * y; }, 
        function identity(e) { return e; }, 
        1)(x, y);
}

function faculty(n){
    return product(1, n);
}

console.log(sum(0, 2));
console.log(sumCubes(0, 5));

console.log(product(1, 5));
console.log(faculty(5));

1 Response
Add your response

Feedback appreciated! :)

over 1 year ago ·