user3246794
user3246794

Reputation:

Why isn't underscore consistent with its type checking?

For example it has isNumber() which uses toString which will detect both primitive numbers and "boxed" numbers.

But later in its code it will use typeof which will not detect boxed values.

I know that typeof is faster but it will miss boxed values.

This issue was brought up in my code base as well, and why I ask the question. Something to the effect of "if you don't use your own functions why would someone else".

Is there something I'm missing here:

Use of typeof

if (typeof isSorted == 'number') {

isNumber defenition

_.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {
    _['is' + name] = function(obj) {
      return toString.call(obj) === '[object ' + name + ']';
    };
  });

Upvotes: 1

Views: 153

Answers (1)

Evan Davis
Evan Davis

Reputation: 36592

That line is part of a method which expects either a boolean or number as its third argument.

_.indexOf = function(array, item, isSorted) {
    if (array == null) return -1;
    var i = 0, length = array.length;
    if (isSorted) {
      if (typeof isSorted == 'number') {
        i = isSorted < 0 ? Math.max(0, length + isSorted) : isSorted;
      } else {
        i = _.sortedIndex(array, item);
        return array[i] === item ? i : -1;
      }
    }
    for (; i < length; i++) if (array[i] === item) return i;
    return -1;
  };

If you pass it something unexpected (like a boxed number) it will barf, and that's your problem, not theirs.

Upvotes: 1

Related Questions