Array Methods

Example of various array methods.

by klenwell

HTML

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

JavaScript

(function () {
    var list, listCopy;

    module("array tests", {
        setup: function () {
            list = [1, 2, 3];
            listCopy = list.slice(0);
            listAltered = list.slice(0);
            listAltered.splice(0, 1);
        },
        teardown: function () {
            list = [];
            listCopy = [];
            listAltered = [];
        }
    });

    test("array methods", function () {
        deepEqual(
            list.map(function (i) {
                return i % 2 == 0;
            }), 
            [false, true, false],
            "map test failed"
        );
        equal(
            list.every(function (i) {
                return i % 2 == 0;
            }),
            false,
            "every test failed"
        );
        equal(
            list.some(function (i) {
                 return i % 2 == 0;
            }),
            true,
            "some test failed"
        );
        deepEqual(
            list.filter(function (i) {
                return i % 2 == 0;
            }), 
            [2],
            "filter test failed"
        );
    });

    test("copy array", function () {
        deepEqual(
            list,
            listCopy,
            "array copy failed"
        );
        notDeepEqual(
            list, 
            listAltered,
            "array not dereferenced"
        );
    });
})();