Chapter 2 - function polymorphism

by Denise Nepraunig

HTML

<link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-1.14.0.css">
<script src="http://code.jquery.com/qunit/qunit-1.14.0.js"></script>
<div id="qunit"></div>
<div id="qunit-fixture"></div>

JavaScript

// 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');
});