Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the passed parameter 'guard' check in underscore.js functions?

Get the first element of an array. Passing n will return the first N values in the array. Aliased as head and take. The guard check allows it to work with _.map.

  _.first = _.head = _.take = function(array, n, guard) {
    if (array == null) return void 0;
    return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
  };

What is the use of the variable 'guard' in this underscore.js function?

like image 295
Adam S Avatar asked Nov 19 '25 16:11

Adam S


1 Answers

If you look at the source code:

  // Get the first element of an array. Passing **n** will return the first N
  // values in the array. Aliased as `head` and `take`. The **guard** check
  // allows it to work with `_.map`.
  _.first = _.head = _.take = function(array, n, guard) {
    if (array == null) return void 0;
    return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
  };

The guard check allows it to work with _.map.

So if you have an array like this:

var a = [ [1, 2, 3], [4, 5, 6] ];
// put this array though _.map and _.first
_.map(a, _.first); // [1, 4]

If this wasn't the case you result would look like this:

[ [], [4] ]

Because of the arguments going into _.map:

_.map(['a', 'b', 'c'], function(val, key, obj) {
    // key = 0, 1, 2
    // val = a, b, c
    // obj = ['a', 'b', 'c'] 
    // the obj argument is why `guard` is truly and the first element in the array is returned rater than using [].slice
});

Its not beautiful but it allows it to work together:

_.first([1, 2, 3], 2) // [1, 2]
_.first([1, 2, 3], 2, true) // 1
_.first([1, 2, 3], 2, 3) // 1
like image 197
Andreas Louv Avatar answered Nov 22 '25 06:11

Andreas Louv