Chapter 2 - functional programming

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
// functional programming

/* functional programming is a style of programming that uses higher-order function. A higher order function treats functions as data -> either taking functions as an argument or returning a function as an result */

var shows = [
        {
            artist: 'Kreap',
            city: 'Melbourne',
            ticketPrice: '40' // why the hell a string?
        },
        {
            artist: 'DJ EQ',
            city: 'Paris',
            ticketPrice: '38'
        },
        {
            artist: 'Treasure Fingers',
            city: 'London',
            ticketPrice: '60'
        }
    ],
    books = [
        {
            title: 'How to DJ Proper',
            price: '18'
        },
        {
            title: 'Music Marketing for Dummies',
            price: '26'
        },
        {
            title: 'Turntablism for Beginners',
            price: '15'
        }
    ];

QUnit.test('Datatype abstraction', function(assert) {
    var sortedShows = shows.sort(function (a,b) {
            return a.ticketPrice < b.ticketPrice;
        }),
        sortedBooks = books.sort(function(a, b) {
            return a.price < b.price;        
        });
    
    assert.ok(sortedShows[0].ticketPrice >
              sortedShows[2].ticketPrice, 
              'Shows sorted correctly.');
    assert.ok(sortedBooks[0].price > 
              sortedBooks[1].price,
              'Books sorted correctly');
              
});