Skip to content

Commit

Permalink
Added tests for _.callIfExists and _.functionExists.
Browse files Browse the repository at this point in the history
  • Loading branch information
Kevin Malakoff committed Sep 25, 2011
1 parent d50251f commit 88ba279
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
29 changes: 29 additions & 0 deletions test/objects.js
Expand Up @@ -110,6 +110,35 @@ $(document).ready(function() {
equals(_({x: 1, y: 2}).chain().isEqual(_({x: 1, y: 2}).chain()).value(), true, 'wrapped objects are equal');
});

test("objects: functionExists", function() {
SomeClass = (function() {
function SomeClass() {}
SomeClass.prototype.callMe = function() {};
return SomeClass;
})();

var some_instance = new SomeClass();
ok(_.functionExists(some_instance, 'callMe'), 'callMe exists');
ok(!_.functionExists(some_instance, 'dontCallMe'), 'dontCallMe does not exist');
});

test("objects: callIfExists", function() {
SomeClass = (function() {
function SomeClass() { this.phone_number = null; }
SomeClass.prototype.callMe = function(phone_number) { this.phone_number = phone_number; return this.phone_number; };
return SomeClass;
})();

var some_instance = new SomeClass(), result;
ok(!some_instance.phone_number, 'no phone number');
result = _.callIfExists(some_instance, 'callMe', '555-555-5555');
ok(result==='555-555-5555', 'callMe made the change');
ok(some_instance.phone_number=='555-555-5555', 'callMe made the change');

result = _.callIfExists(some_instance, 'dontCallMe');
ok(!result, 'silently ignored');
});

test("objects: isEmpty", function() {
ok(!_([1]).isEmpty(), '[1] is not empty');
ok(_.isEmpty([]), '[] is empty');
Expand Down
2 changes: 1 addition & 1 deletion underscore.js
Expand Up @@ -1015,7 +1015,7 @@

// Call a function if it exists on an object.
_.callIfExists = function(object, function_name) {
return _.functionExists(object, function_name) ? object[function_name].apply(object, arguments.slice(2)) : undefined;
return _.functionExists(object, function_name) ? object[function_name].apply(object, slice.call(arguments, 2)) : undefined;
};

// Get your super classes' constructor if it exists. Can be useful when dynamically updating a hierarchy.
Expand Down

0 comments on commit 88ba279

Please sign in to comment.