map.js 1.64 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
var map = require('../');
var test = require('tape');

test('numbers -> letters', function (t) {
    t.plan(2);
    var a = map([97,98,99], function (c) {
        return String.fromCharCode(c);
    });
    t.equal(a.join(''), 'abc');
    
    var b = map(cripple([97,98,99]), function (c) {
        return String.fromCharCode(c);
    });
    t.equal(b.join(''), 'abc');
});

test('elements and indexes', function (t) {
    t.plan(8);
    var x = { q: 5 }, y = 3, z = null;
    
    t.deepEqual(
        map([x,y,z], function (c, i) { return i }),
        [ 0, 1, 2 ],
        'index check'
    );
    t.deepEqual(
        map([x,y,z], function (c, i) { return i }),
        [ 0, 1, 2 ],
        'crippled index check'
    );
    
    var xs0 = [ x, y, z ];
    map(xs0, function (c, i, xs) {
        t.strictEqual(xs, xs0, 'argument[2]');
    });
    var xs1 = [ x, y, z ];
    map(xs1, function (c, i, xs) {
        t.strictEqual(xs, xs1, 'crippled argument[2]');
    });
});

test('ignore holes', function (t) {
    t.plan(2);
    t.deepEqual(
        map(new Array(5), function (x) { return x }),
        []
    );
    t.deepEqual(
        map(cripple(new Array(5)), function (x) { return x }),
        []
    );
});

test('sparse map', function (t) {
    t.plan(2);
    var xs = new Array(5);
    xs[2] = 'a';
    xs[4] = 'b';
    t.equal(
        map(xs, function (x, i) { return x + i }).join(''),
        'a2b4'
    );
    
    var ys = new Array(5);
    ys[2] = 'a';
    ys[4] = 'b';
    t.equal(
        map(cripple(xs), function (x, i) { return x + i }).join(''),
        'a2b4'
    );
    t.end();
});

function cripple (xs) {
    xs.map = undefined;
    return xs;
}