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);
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.
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.
The _. map() method creates an array of values by running each element in collection through the iteratee.
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;
});
});
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;
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With