Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underscore functional javascript

I'm trying to switch in general to functional programming and want to use underscore for JavaScript.

But I'm stuck at first base. I could not create an array at all and resorted to imperative language, and I can't seem to transform them properly either: n.length is correct, but n[0].length is undefined (see fiddle)

var a = new Array(5);
for (i = 0; i < a.length; i++) {
    a[i] = new Array(6);
}
var n = _.map(a, function (row, rowIdx) {
    _.map(row, function(col, colIdx) {
        return rowIdx * colIdx
    });
});

console.log(a.length)
console.log(n.length)
console.log(a[0].length);
console.log(n[0].length);
like image 283
Simon H Avatar asked Dec 17 '13 17:12

Simon H


People also ask

Can JavaScript function include underscore?

Underscore ( _ ) is just a plain valid character for variable/function name, it does not bring any additional feature. However, it is a good convention to use underscore to mark variable/function as private. You can check Underscore prefix for property and method names in JavaScript for some previous discussion.

How does _ Reduce Work?

The _. reduce() method reduces collection to value which is accumulated result of running each element in the collection through iteratee, where each successive invocation is supplied return value of the previous. The first element of the collection is used as the initial value, if accumulator is not given.

What is _ map in JavaScript?

The _. map() method creates an array of values by running each element in collection through the iteratee.


2 Answers

To "functionally" create a 5 x 6 matrix using underscore, you could do something like this:

var matrix = _.range(5).map(function (i) {
    return _.range(6).map(function (j) {
        return j * i;
    });
});

The _.range function (documentation) is a shorthand for creating arrays that are filled with sequential numbers. For example, _.range(5) returns the array [0,1,2,3,4]. Ranges start at zero.

If you didn't want to use _.range, you could do this with raw JavaScript by using array literals:

var matrix = [0,1,2,3,4].map(function (i) {
    return [0,1,2,3,4,5].map(function (j) {
        return j * i;
    });
});
like image 151
rossipedia Avatar answered Oct 13 '22 16:10

rossipedia


Another way to create a matrix would be to use _.times:

var matrix = _.times(6, function(x){
    return _.times(7, function(y){

        // do whatever needs to be done to calculate the value at x,y

        return x + ',' + y;
    });
}); 
like image 29
Gruff Bunny Avatar answered Oct 13 '22 15:10

Gruff Bunny