// Programming JavaScript Applications
// Chapter 2
// function polymorphism
/* in computer science, polymorphism measn somethings behaves differntly based on context */
function sort() {
var args = [].slice.call(arguments, 0);
return args.sort();
}
console.log(sort(9, 7, 4).toString());
QUnit.test("arguments as array", function(assert) {
assert.equal(sort(9, 7, 4).toString(), "4,7,9", "sorting works");
});
function morph(options) {
var args = [].slice.call(arguments, 0),
animals = 'turtles';
// options contains only one argument, because it is a declared var
console.log('options:', options);
console.log('arguments:', arguments);
if (typeof options === 'string') {
animals = options;
args.shift();
}
return('The pet store has ' + args + ' ' + animals + '.');
}
//morph('cats', 3);
//morph('dogs', 5);
QUnit.test("Polymorphic branching", function(assert) {
var test1 = morph('cats', 3),
test2 = morph('dogs', 4),
test3 = morph(2);
assert.equal(test1, 'The pet store has 3 cats.', '3 cats');
assert.equal(test2, 'The pet store has 4 dogs.', '4 dogs');
assert.equal(test3, 'The pet store has 2 turtles.', '2 turtles');
});
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.