<commit_before>if (!dp) var dp = {};

dp.ui = {
    _initiated: false,
    init: function(obj) {
        if (!obj && dp.ui._initiated) return;
        dp.ui._initiated = true;
        dp.ui.element.init(obj);
    },
    util: {
        _alert_template: undefined,
        alert_focus: undefined,
        alert: function(a, b, c, d, e) {
            if (dp.ui.util._alert_template == undefined) {
                dp.ui.util._alert_template = dp_jqlib('
').addClass('dp4css-alert');
                dp.ui.util._alert_template.append(dp_jqlib('
').addClass('_bg'));

                var _box = dp_jqlib('
').addClass('_box');

                _box.append(dp_jqlib('
').addClass('_msg'));
                _box.append(dp_jqlib('
').addClass('_ico').text('!'));
                _box.append(dp_jqlib('
').addClass('_btn'));

                dp.ui.util._alert_template.append(_box);
            }

            var template = dp.ui.util._alert_template.clone();
            template.attr('id', 'uniqid-' + dp.helper.string.uniqid());

            var bg = template.find('._bg');
            var message = template.find('._msg');
            var button = template.find('._btn');
            var box = template.find('._box');

            var _msg = undefined;
            var _msg_html = undefined;
            var _buttons = [];

            if (typeof(a) == 'object' && !b && !c && !d && !e) {
                if (a.message && a.html) {
                    _msg_html = a.message;
                }
                else if (a.message) {
                    _msg = a.message;
                }

                if (a.buttons) {
                    for (var i in a.buttons) {
                        _buttons.push([a.buttons[i][0], a.buttons[i][1]]);
                    }
                }
            }
            else if (typeof(a) == 'string' && !b && !c && !d && !e) {
                _msg = a;

                if (b === null) {

                }
                else {
                    _buttons.push(['OK', undefined]);
                }
            }
            else if (typeof(a) == 'string' && typeof(b) == 'string' && !c && !d && !e) {
                _msg = a;
                _buttons.push([b, undefined]);
            }
            else if (typeof(a) == 'string' && typeof(b) == 'function' && !c && !d && !e) {
                _msg = a;
                _buttons.push(['OK', b]);
            }
            else if (typeof(a) == 'string' && typeof(b) == 'function' && typeof(c) == 'string' && !d && !e) {
                _msg = a;
                _buttons.push([c, b]);
            }
            else if (typeof(a) == 'string' && typeof(b) == 'function' && typeof(c) == 'function' && !d && !e) {
                _msg = a;
                _buttons.push(['OK', b]);
                _buttons.push(['Cancel', c]);
            }
            else if (typeof(a) == 'string' && typeof(b) == 'function' && typeof(c) == 'string' && typeof(d) == 'function' && !e) {
                _msg = a;
                _buttons.push([c, b]);
                _buttons.push(['Cancel', d]);
            }
            else if (typeof(a) == 'string' && typeof(b) == 'function' && typeof(c) == 'string' && typeof(d) == 'function' && typeof(e) == 'string') {
                _msg = a;
                _buttons.push([c, b]);
                _buttons.push([e, d]);
            }

            if (_msg_html) {
                message.html(_msg_html);
            }
            else if (_msg) {
                message.text(_msg);
                message.html(message.text().replace(/\n/gi, '
'));
            }

            var box_height = 0;
            var pongdang = 15;
            var delegate = undefined;

            var _dismiss = function() {
                box.animate({
                    'margin-top': (((box_height / 2) + 30) * -1) + 'px'
                }, 150, function() {
                    box.animate({
                        'margin-top': (((box_height / 2) - 70) * -1) + 'px',
                        'opacity': 0
                    }, 150);

                    bg.fadeTo(300, 0, function() {
                        template.remove();

                        if (dp.ui.util.alert_focus) {
                            dp.ui.util.alert_focus.focus();
                            dp.ui.util.alert_focus = undefined;
                        }

                        if (delegate) {
                            delegate(template);
                        }
                    });
                });
            };

            dp_jqlib(_buttons).each(function(k, e) {
                var btn = dp_jqlib('<button />');
                btn.addClass('_i-' + k);
                btn.text(e[0]);
                btn.click(function() {
                    if (e[1] && typeof(e[1]) == 'function') {
                        delegate = e[1];
                    }

                    _dismiss();
                });

                button.append(btn);
            });

            dp_jqlib('body').append(template);

            box_height = box.height();

            var bg_opacity = parseFloat(bg.css('opacity'));

            bg.fadeTo(0, 0.001);
            box.fadeTo(0, 0.001);
            box.css('margin-top', (((box_height / 2) + 70) * -1) + 'px');

            bg.fadeTo(200, bg_opacity);
            box.delay(50).animate({
                'margin-top': (((box_height / 2) - 10) * -1) + 'px',
                'opacity': 1.0
            }, 200, function() {
                box.animate({
                    'margin-top': ((box_height / 2 + 5) * -1) + 'px'
                }, 150, function() {
                    box.animate({
                        'margin-top': ((box_height / 2) * -1) + 'px'
                    }, 150);
                });
            });

            if (button) {
                button.find('._i-0').focus();
            }

            return template;
        },
        noti: function(a, b, c, d) {
            alert('not implemented yet.');
        }
    },
    element: {
        init: function(obj) {
            dp.ui.element.input.delegate.on_return(obj);
            dp.ui.element.input.delegate.on_focus(obj);
            dp.ui.element.input.delegate.on_focusout(obj);
            dp.ui.element.input.delegate.on_keyup(obj);
            dp.ui.element.input.delegate.on_keydown(obj);
        },
        input: {
            delegate: {
                on_return: function(obj) {
                    if (!obj) obj = dp_jqlib('body');
                    obj.find('input[dp-on-return][dp-on-return-installed!=yes]').each(function() {
                        var _id = dp_jqlib(this).attr('id') || 'uniqid-' + dp.helper.string.uniqid();

                        dp_jqlib(this).attr('id', _id);
                        dp_jqlib(this).attr('dp-on-return-installed', 'yes');

                        dp_jqlib(this).keypress(function(e) {
                            if (dp_jqlib(this).attr('dp-on-return-busy') == 'yes') {
                                return;
                            }

                            if (e.keyCode == 13) {
                                var delegate;

                                try {
                                    delegate = eval(dp_jqlib(this).attr('dp-on-return'));
                                }catch(_){}

                                if (delegate && typeof(delegate) == 'function') {
                                    dp_jqlib(this).attr('dp-on-return-busy', 'yes');
                                    setTimeout(delegate(dp_jqlib(this)), 0);
                                    setTimeout("dp_jqlib('#" + _id + "').attr('dp-on-return-busy', 'no');", 150);

                                    e.preventDefault();
                                }
                            }
                        });
                    });
                },
                on_focus: function(obj) {
                    if (!obj) obj = dp_jqlib('body');
                    obj.find('input[dp-on-focus][dp-on-focus-installed!=yes]').each(function() {
                        var _id = dp_jqlib(this).attr('id') || 'uniqid-' + dp.helper.string.uniqid();

                        dp_jqlib(this).attr('id', _id);
                        dp_jqlib(this).attr('dp-on-focus-installed', 'yes');

                        dp_jqlib(this).focus(function(e) {
                            var delegate;

                            try {
                                delegate = eval(dp_jqlib(this).attr('dp-on-focus'));
                            }catch(_){}

                            if (delegate && typeof(delegate) == 'function') {
                                setTimeout(delegate(dp_jqlib(this)), 0);
                            }
                        });
                    });
                },
                on_focusout: function(obj) {
                    if (!obj) obj = dp_jqlib('body');
                    obj.find('input[dp-on-focusout][dp-on-focusout-installed!=yes]').each(function() {
                        var _id = dp_jqlib(this).attr('id') || 'uniqid-' + dp.helper.string.uniqid();

                        dp_jqlib(this).attr('id', _id);
                        dp_jqlib(this).attr('dp-on-focusout-installed', 'yes');

                        dp_jqlib(this).focusout(function(e) {
                            var delegate;

                            try {
                                delegate = eval(dp_jqlib(this).attr('dp-on-focusout'));
                            }catch(_){}

                            if (delegate && typeof(delegate) == 'function') {
                                setTimeout(delegate(dp_jqlib(this)), 0);
                            }
                        });
                    });
                },
                on_keyup: function(obj) {
                    if (!obj) obj = dp_jqlib('body');
                    obj.find('input[dp-on-keyup][dp-on-keyup-installed!=yes]').each(function() {
                        var _id = dp_jqlib(this).attr('id') || 'uniqid-' + dp.helper.string.uniqid();

                        dp_jqlib(this).attr('id', _id);
                        dp_jqlib(this).attr('dp-on-keyup-installed', 'yes');

                        dp_jqlib(this).keyup(function(e) {
                            var delegate;
                            try {
                                delegate = eval(dp_jqlib(this).attr('dp-on-keyup'));
                            }catch(_){}

                            if (delegate && typeof(delegate) == 'function') {
                                setTimeout(delegate(dp_jqlib(this)), 0);
                            }
                        });
                    });
                },
                on_keydown: function(obj) {
                    if (!obj) obj = dp_jqlib('body');
                    obj.find('input[dp-on-keydown][dp-on-keydown-installed!=yes]').each(function() {
                        var _id = dp_jqlib(this).attr('id') || 'uniqid-' + dp.helper.string.uniqid();

                        dp_jqlib(this).attr('id', _id);
                        dp_jqlib(this).attr('dp-on-keydown-installed', 'yes');

                        dp_jqlib(this).keydown(function(e) {
                            var delegate;
                            try {
                                delegate = eval(dp_jqlib(this).attr('dp-on-keydown'));
                            }catch(_){}

                            if (delegate && typeof(delegate) == 'function') {
                                setTimeout(delegate(dp_jqlib(this)), 0);
                            }
                        });
                    });
                }
            }
        }
    }
};

dp_init(function() {
    dp.init();
});
<commit_msg>add event data as argument.<commit_after>if (!dp) var dp = {};

dp.ui = {
    _initiated: false,
    init: function(obj) {
        if (!obj && dp.ui._initiated) return;
        dp.ui._initiated = true;
        dp.ui.element.init(obj);
    },
    util: {
        _alert_template: undefined,
        alert_focus: undefined,
        alert: function(a, b, c, d, e) {
            if (dp.ui.util._alert_template == undefined) {
                dp.ui.util._alert_template = dp_jqlib('
').addClass('dp4css-alert');
                dp.ui.util._alert_template.append(dp_jqlib('
').addClass('_bg'));

                var _box = dp_jqlib('
').addClass('_box');

                _box.append(dp_jqlib('
').addClass('_msg'));
                _box.append(dp_jqlib('
').addClass('_ico').text('!'));
                _box.append(dp_jqlib('
').addClass('_btn'));

                dp.ui.util._alert_template.append(_box);
            }

            var template = dp.ui.util._alert_template.clone();
            template.attr('id', 'uniqid-' + dp.helper.string.uniqid());

            var bg = template.find('._bg');
            var message = template.find('._msg');
            var button = template.find('._btn');
            var box = template.find('._box');

            var _msg = undefined;
            var _msg_html = undefined;
            var _buttons = [];

            if (typeof(a) == 'object' && !b && !c && !d && !e) {
                if (a.message && a.html) {
                    _msg_html = a.message;
                }
                else if (a.message) {
                    _msg = a.message;
                }

                if (a.buttons) {
                    for (var i in a.buttons) {
                        _buttons.push([a.buttons[i][0], a.buttons[i][1]]);
                    }
                }
            }
            else if (typeof(a) == 'string' && !b && !c && !d && !e) {
                _msg = a;

                if (b === null) {

                }
                else {
                    _buttons.push(['OK', undefined]);
                }
            }
            else if (typeof(a) == 'string' && typeof(b) == 'string' && !c && !d && !e) {
                _msg = a;
                _buttons.push([b, undefined]);
            }
            else if (typeof(a) == 'string' && typeof(b) == 'function' && !c && !d && !e) {
                _msg = a;
                _buttons.push(['OK', b]);
            }
            else if (typeof(a) == 'string' && typeof(b) == 'function' && typeof(c) == 'string' && !d && !e) {
                _msg = a;
                _buttons.push([c, b]);
            }
            else if (typeof(a) == 'string' && typeof(b) == 'function' && typeof(c) == 'function' && !d && !e) {
                _msg = a;
                _buttons.push(['OK', b]);
                _buttons.push(['Cancel', c]);
            }
            else if (typeof(a) == 'string' && typeof(b) == 'function' && typeof(c) == 'string' && typeof(d) == 'function' && !e) {
                _msg = a;
                _buttons.push([c, b]);
                _buttons.push(['Cancel', d]);
            }
            else if (typeof(a) == 'string' && typeof(b) == 'function' && typeof(c) == 'string' && typeof(d) == 'function' && typeof(e) == 'string') {
                _msg = a;
                _buttons.push([c, b]);
                _buttons.push([e, d]);
            }

            if (_msg_html) {
                message.html(_msg_html);
            }
            else if (_msg) {
                message.text(_msg);
                message.html(message.text().replace(/\n/gi, '
'));
            }

            var box_height = 0;
            var pongdang = 15;
            var delegate = undefined;

            var _dismiss = function() {
                box.animate({
                    'margin-top': (((box_height / 2) + 30) * -1) + 'px'
                }, 150, function() {
                    box.animate({
                        'margin-top': (((box_height / 2) - 70) * -1) + 'px',
                        'opacity': 0
                    }, 150);

                    bg.fadeTo(300, 0, function() {
                        template.remove();

                        if (dp.ui.util.alert_focus) {
                            dp.ui.util.alert_focus.focus();
                            dp.ui.util.alert_focus = undefined;
                        }

                        if (delegate) {
                            delegate(template);
                        }
                    });
                });
            };

            dp_jqlib(_buttons).each(function(k, e) {
                var btn = dp_jqlib('<button />');
                btn.addClass('_i-' + k);
                btn.text(e[0]);
                btn.click(function() {
                    if (e[1] && typeof(e[1]) == 'function') {
                        delegate = e[1];
                    }

                    _dismiss();
                });

                button.append(btn);
            });

            dp_jqlib('body').append(template);

            box_height = box.height();

            var bg_opacity = parseFloat(bg.css('opacity'));

            bg.fadeTo(0, 0.001);
            box.fadeTo(0, 0.001);
            box.css('margin-top', (((box_height / 2) + 70) * -1) + 'px');

            bg.fadeTo(200, bg_opacity);
            box.delay(50).animate({
                'margin-top': (((box_height / 2) - 10) * -1) + 'px',
                'opacity': 1.0
            }, 200, function() {
                box.animate({
                    'margin-top': ((box_height / 2 + 5) * -1) + 'px'
                }, 150, function() {
                    box.animate({
                        'margin-top': ((box_height / 2) * -1) + 'px'
                    }, 150);
                });
            });

            if (button) {
                button.find('._i-0').focus();
            }

            return template;
        },
        noti: function(a, b, c, d) {
            alert('not implemented yet.');
        }
    },
    element: {
        init: function(obj) {
            dp.ui.element.input.delegate.on_return(obj);
            dp.ui.element.input.delegate.on_focus(obj);
            dp.ui.element.input.delegate.on_focusout(obj);
            dp.ui.element.input.delegate.on_keyup(obj);
            dp.ui.element.input.delegate.on_keydown(obj);
        },
        input: {
            delegate: {
                on_return: function(obj) {
                    if (!obj) obj = dp_jqlib('body');
                    obj.find('input[dp-on-return][dp-on-return-installed!=yes]').each(function() {
                        var _id = dp_jqlib(this).attr('id') || 'uniqid-' + dp.helper.string.uniqid();

                        dp_jqlib(this).attr('id', _id);
                        dp_jqlib(this).attr('dp-on-return-installed', 'yes');

                        dp_jqlib(this).keypress(function(e) {
                            if (dp_jqlib(this).attr('dp-on-return-busy') == 'yes') {
                                return;
                            }

                            if (e.keyCode == 13) {
                                var delegate;

                                try {
                                    delegate = eval(dp_jqlib(this).attr('dp-on-return'));
                                }catch(_){}

                                if (delegate && typeof(delegate) == 'function') {
                                    dp_jqlib(this).attr('dp-on-return-busy', 'yes');
                                    setTimeout(delegate(dp_jqlib(this)), 0);
                                    setTimeout("dp_jqlib('#" + _id + "').attr('dp-on-return-busy', 'no');", 150);

                                    e.preventDefault();
                                }
                            }
                        });
                    });
                },
                on_focus: function(obj) {
                    if (!obj) obj = dp_jqlib('body');
                    obj.find('input[dp-on-focus][dp-on-focus-installed!=yes]').each(function() {
                        var _id = dp_jqlib(this).attr('id') || 'uniqid-' + dp.helper.string.uniqid();

                        dp_jqlib(this).attr('id', _id);
                        dp_jqlib(this).attr('dp-on-focus-installed', 'yes');

                        dp_jqlib(this).focus(function(e) {
                            var delegate;

                            try {
                                delegate = eval(dp_jqlib(this).attr('dp-on-focus'));
                            }catch(_){}

                            if (delegate && typeof(delegate) == 'function') {
                                setTimeout(delegate(dp_jqlib(this), e), 0);
                            }
                        });
                    });
                },
                on_focusout: function(obj) {
                    if (!obj) obj = dp_jqlib('body');
                    obj.find('input[dp-on-focusout][dp-on-focusout-installed!=yes]').each(function() {
                        var _id = dp_jqlib(this).attr('id') || 'uniqid-' + dp.helper.string.uniqid();

                        dp_jqlib(this).attr('id', _id);
                        dp_jqlib(this).attr('dp-on-focusout-installed', 'yes');

                        dp_jqlib(this).focusout(function(e) {
                            var delegate;

                            try {
                                delegate = eval(dp_jqlib(this).attr('dp-on-focusout'));
                            }catch(_){}

                            if (delegate && typeof(delegate) == 'function') {
                                setTimeout(delegate(dp_jqlib(this), e), 0);
                            }
                        });
                    });
                },
                on_keyup: function(obj) {
                    if (!obj) obj = dp_jqlib('body');
                    obj.find('input[dp-on-keyup][dp-on-keyup-installed!=yes]').each(function() {
                        var _id = dp_jqlib(this).attr('id') || 'uniqid-' + dp.helper.string.uniqid();

                        dp_jqlib(this).attr('id', _id);
                        dp_jqlib(this).attr('dp-on-keyup-installed', 'yes');

                        dp_jqlib(this).keyup(function(e) {
                            var delegate;
                            try {
                                delegate = eval(dp_jqlib(this).attr('dp-on-keyup'));
                            }catch(_){}

                            if (delegate && typeof(delegate) == 'function') {
                                setTimeout(delegate(dp_jqlib(this), e), 0);
                            }
                        });
                    });
                },
                on_keydown: function(obj) {
                    if (!obj) obj = dp_jqlib('body');
                    obj.find('input[dp-on-keydown][dp-on-keydown-installed!=yes]').each(function() {
                        var _id = dp_jqlib(this).attr('id') || 'uniqid-' + dp.helper.string.uniqid();

                        dp_jqlib(this).attr('id', _id);
                        dp_jqlib(this).attr('dp-on-keydown-installed', 'yes');

                        dp_jqlib(this).keydown(function(e) {
                            var delegate;
                            try {
                                delegate = eval(dp_jqlib(this).attr('dp-on-keydown'));
                            }catch(_){}

                            if (delegate && typeof(delegate) == 'function') {
                                setTimeout(delegate(dp_jqlib(this), e), 0);
                            }
                        });
                    });
                }
            }
        }
    }
};

dp_init(function() {
    dp.init();
});
<|endoftext|>


<commit_before>describe("About Arrays", function() {

  //We shall contemplate truth by testing reality, via spec expectations.
  it("should create arrays", function() {
    var emptyArray = [];
    expect(typeof(emptyArray)).toBe(FILL_ME_IN); //A mistake? - http:javascript.crockford.com/remedial.html
    expect(emptyArray.length).toBe(FILL_ME_IN);

    var multiTypeArray = [0, 1, "two", function () { return 3; }, {value1: 4, value2: 5}, [6, 7]];
    expect(multiTypeArray[0]).toBe(FILL_ME_IN);
    expect(multiTypeArray[2]).toBe(FILL_ME_IN);
    expect(multiTypeArray[3]()).toBe(FILL_ME_IN);
    expect(multiTypeArray[4].value1).toBe(FILL_ME_IN);
    expect(multiTypeArray[4]["value2"]).toBe(FILL_ME_IN);
    expect(multiTypeArray[5][0]).toBe(FILL_ME_IN);
  });

  it("should understand array literals", function () {
    var array = [];
    expect(array).toEqual([]);

    array[0] = 1;
    expect(array).toEqual([1]);

    array[1] = 2;
    expect(array).toEqual([1, FILL_ME_IN]);

    array.push(3);
    expect(array).toEqual(FILL_ME_IN);
  });

  it("should understand array length", function () {
    var fourNumberArray = [1, 2, 3, 4];

    expect(fourNumberArray.length).toBe(FILL_ME_IN);
    fourNumberArray.push(5, 6);
    expect(fourNumberArray.length).toBe(FILL_ME_IN);

    var tenEmptyElementArray = new Array(10);
    expect(tenEmptyElementArray.length).toBe(FILL_ME_IN);

    tenEmptyElementArray.length = 5;
    expect(tenEmptyElementArray.length).toBe(FILL_ME_IN);
  });

  it("should slice arrays", function () {
    var array = ["peanut", "butter", "and", "jelly"];

    expect(array.slice(0, 1)).toEqual(FILL_ME_IN);
    expect(array.slice(0, 2)).toEqual(FILL_ME_IN);
    expect(array.slice(2, 2)).toEqual(FILL_ME_IN);
    expect(array.slice(2, 20)).toEqual(FILL_ME_IN);
    expect(array.slice(3, 0)).toEqual(FILL_ME_IN);
    expect(array.slice(3, 100)).toEqual(FILL_ME_IN);
    expect(array.slice(5, 1)).toEqual(FILL_ME_IN);
  });

  it("should know array references", function () {
    var array = [ "zero", "one", "two", "three", "four", "five" ];

    function passedByReference(refArray) {
      refArray[1] = "changed in function";
    }
    passedByReference(array);
    expect(array[1]).toBe(FILL_ME_IN);

    var assignedArray = array;
    assignedArray[5] = "changed in assignedArray";
    expect(array[5]).toBe(FILL_ME_IN);

    var copyOfArray = array.slice();
    copyOfArray[3] = "changed in copyOfArray";
    expect(array[3]).toBe(FILL_ME_IN);
  });

  it("should push and pop", function () {
    var array = [1, 2];
    array.push(3);

    expect(array).toEqual(FILL_ME_IN);

    var poppedValue = array.pop();
    expect(poppedValue).toBe(FILL_ME_IN);
    expect(array).toEqual(FILL_ME_IN);
  });

  it("should know about shifting arrays", function () {
    var array = [1, 2];

    array.unshift(3);
    expect(array).toEqual(FILL_ME_IN);

    var shiftedValue = array.shift();
    expect(shiftedValue).toEqual(FILL_ME_IN);
    expect(array).toEqual(FILL_ME_IN);
  });
});
<commit_msg>Completed AboutArrays Koans<commit_after>describe("About Arrays", function() {

  //We shall contemplate truth by testing reality, via spec expectations.
  it("should create arrays", function() {
    var emptyArray = [];
    expect(typeof(emptyArray)).toBe("object"); //A mistake? - http:javascript.crockford.com/remedial.html
    expect(emptyArray.length).toBe(0);

    var multiTypeArray = [0, 1, "two", function () { return 3; }, {value1: 4, value2: 5}, [6, 7]];
    expect(multiTypeArray[0]).toBe(0);
    expect(multiTypeArray[2]).toBe("two");
    expect(multiTypeArray[3]()).toBe(3);
    expect(multiTypeArray[4].value1).toBe(4);
    expect(multiTypeArray[4]["value2"]).toBe(5);
    expect(multiTypeArray[5][0]).toBe(6);
  });

  it("should understand array literals", function () {
    var array = [];
    expect(array).toEqual([]);

    array[0] = 1;
    expect(array).toEqual([1]);

    array[1] = 2;
    expect(array).toEqual([1, 2]);

    array.push(3);
    expect(array).toEqual([1, 2, 3]);
  });

  it("should understand array length", function () {
    var fourNumberArray = [1, 2, 3, 4];

    expect(fourNumberArray.length).toBe(4);
    fourNumberArray.push(5, 6);
    expect(fourNumberArray.length).toBe(6);

    var tenEmptyElementArray = new Array(10);
    expect(tenEmptyElementArray.length).toBe(10);

    tenEmptyElementArray.length = 5;
    expect(tenEmptyElementArray.length).toBe(5);
  });

  it("should slice arrays", function () {
    var array = ["peanut", "butter", "and", "jelly"];

    expect(array.slice(0, 1)).toEqual(["peanut"]);
    expect(array.slice(0, 2)).toEqual(["peanut", "butter"]);
    expect(array.slice(2, 2)).toEqual([]);
    expect(array.slice(2, 20)).toEqual(["and", "jelly"]);
    expect(array.slice(3, 0)).toEqual([]);
    expect(array.slice(3, 100)).toEqual(["jelly"]);
    expect(array.slice(5, 1)).toEqual([]);
  });

  it("should know array references", function () {
    var array = [ "zero", "one", "two", "three", "four", "five" ];

    function passedByReference(refArray) {
      refArray[1] = "changed in function";
    }
    passedByReference(array);
    expect(array[1]).toBe("changed in function");

    var assignedArray = array;
    assignedArray[5] = "changed in assignedArray";
    expect(array[5]).toBe("changed in assignedArray");

    var copyOfArray = array.slice();
    copyOfArray[3] = "changed in copyOfArray";
    expect(array[3]).toBe("three");
  });

  it("should push and pop", function () {
    var array = [1, 2];
    array.push(3);

    expect(array).toEqual([1, 2, 3]);

    var poppedValue = array.pop();
    expect(poppedValue).toBe(3);
    expect(array).toEqual([1, 2]);
  });

  it("should know about shifting arrays", function () {
    var array = [1, 2];

    array.unshift(3);
    expect(array).toEqual([3, 1, 2]);

    var shiftedValue = array.shift();
    expect(shiftedValue).toEqual(3);
    expect(array).toEqual([1, 2]);
  });
});
<|endoftext|>


<commit_before>import elrUtlities from './elr-utilities';
const $ = require('jquery');

let elr = elrUtlities();

const elrLightbox = function(params) {
    const self = {};
    const spec = params || {};
    const $images = spec.images || $('ul.elr-lightbox-thumbnails');
    const speed = spec.speed || 300;

    const createThumbnails = function(list) {
        const $links = list.find('a');
        let thumbnailList = [];
        let thumbnails = '';

        $links.each(function() {
            thumbnailList.push($(this).attr('href'));
        });

        $.each(thumbnailList, function(k, v) {
            thumbnails += `<li><a href=${v}><img src=${v}></a></li>`;
        });

        return thumbnails;
    };

    const createLightbox = function(thumbnails, speed) {
        const img = $(this).attr('href');

        const $imgVisible = elr.createElement('img', {
            class: 'img-visible',
            src: img,
            alt: 'thumbnail'
        });

        const $close = elr.createElement('button', {
            class: 'close',
            text: 'x'
        });

        const $thumbnails = elr.createElement('ul', {
            class: 'thumbnail-list',
            html: thumbnails
        });

        const $nav = elr.createElement('div', {
            class: 'lightbox-nav',
            html: '<button class="prev" data-dir="prev"></button><button class="next" data-dir="next"></button>'
        });

        const $lightbox = elr.createElement('div', {
            class: 'elr-blackout'
        });

        $lightbox.hide().appendTo('body').fadeIn(speed, function() {
            $close.appendTo($lightbox);
            $imgVisible.appendTo($lightbox);
            $nav.appendTo($lightbox);
            $thumbnails.appendTo($lightbox);
        });
    };

    const advanceImage = function(direction) {
        const $list = $('.thumbnail-list');
        const $currentImg = $('div.elr-blackout img.img-visible');
        const currentImgSrc = $currentImg.attr('src');
        const $currentThumb = $list.find(`img[src$="${currentImgSrc}"]`).closest('li').index();
        const len = $list.find('li').length - 1;
        // let $nextImg;
        let nextImgIndex;

        if (direction === 'prev') {
            nextImgIndex = ($currentThumb === 0) ? len : $currentThumb - 1;
        } else {
            nextImgIndex = ($currentThumb === len) ? 0 : $currentThumb + 1;
        }

        const $nextImg = $list.find('li').eq(nextImgIndex).find('img').attr('src');
        $currentImg.fadeOut(speed, function() {
            $(this).attr('src', $nextImg).fadeIn(speed);
        });
    };

    const changeImage = function() {
        const img = $(this).attr('href');
        const $oldImg = $('div.elr-blackout img.img-visible');
        const oldImgSrc = $oldImg.attr('src');

        if (oldImgSrc !== img) {
            $oldImg.fadeOut(speed, function() {
                $(this).attr('src', img).fadeIn(speed);
            });
        }
    };

    const removeLightbox = function() {
        $('div.elr-blackout').fadeOut(speed, function() {
            $(this).remove();
        });
    };

    if ($images.length) {
        const thumbnails = createThumbnails($images);
        const $body = $('body');

        $images.on('click', 'a', function(e) {
            e.preventDefault();
            createLightbox.call(this, thumbnails, speed);
        });

        $body.on('click', 'div.elr-blackout button.close', removeLightbox);
        $body.on('click', 'div.elr-blackout', function(e) {
            removeLightbox();
            e.stopPropagation();
        });

        $body.on('click', 'div.elr-blackout ul.thumbnail-list a', function(e) {
            e.preventDefault();
            e.stopPropagation();
            changeImage.call(this);
        });

        elr.killEvent($body, 'click', 'div.elr-blackout .img-visible');
        elr.killEvent($body, 'click', 'div.elr-blackout .lightbox-nav');

        $body.on('click', 'div.elr-blackout .lightbox-nav button', function(e) {
            const direction = $(this).data('dir');

            e.preventDefault();
            e.stopPropagation();
            advanceImage(direction);
        });

        $body.on('keydown', function(e) {
            if (e.which === 37) {
                advanceImage('prev');
            } else if (e.which === 39) {
                advanceImage('next');
            }
        });

        $body.on('keydown', function(e) {
            if (e.which === 27) {
                removeLightbox();
            }
        });
    }

    return self;
};

export default elrLightbox;<commit_msg>fix bug where lightbox didn't close when clicking on nav<commit_after>import elrUtlities from './elr-utilities';
const $ = require('jquery');

let elr = elrUtlities();

const elrLightbox = function(params) {
    const self = {};
    const spec = params || {};
    const $images = spec.images || $('ul.elr-lightbox-thumbnails');
    const speed = spec.speed || 300;

    const createThumbnails = function(list) {
        const $links = list.find('a');
        let thumbnailList = [];
        let thumbnails = '';

        $links.each(function() {
            thumbnailList.push($(this).attr('href'));
        });

        $.each(thumbnailList, function(k, v) {
            thumbnails += `<li><a href=${v}><img src=${v}></a></li>`;
        });

        return thumbnails;
    };

    const createLightbox = function(thumbnails, speed) {
        const img = $(this).attr('href');

        const $imgVisible = elr.createElement('img', {
            class: 'img-visible',
            src: img,
            alt: 'thumbnail'
        });

        const $close = elr.createElement('button', {
            class: 'close',
            text: 'x'
        });

        const $thumbnails = elr.createElement('ul', {
            class: 'thumbnail-list',
            html: thumbnails
        });

        const $nav = elr.createElement('div', {
            class: 'lightbox-nav',
            html: '<button class="prev" data-dir="prev"></button><button class="next" data-dir="next"></button>'
        });

        const $lightbox = elr.createElement('div', {
            class: 'elr-blackout'
        });

        $lightbox.hide().appendTo('body').fadeIn(speed, function() {
            $close.appendTo($lightbox);
            $imgVisible.appendTo($lightbox);
            $nav.appendTo($lightbox);
            $thumbnails.appendTo($lightbox);
        });
    };

    const advanceImage = function(direction) {
        const $list = $('.thumbnail-list');
        const $currentImg = $('div.elr-blackout img.img-visible');
        const currentImgSrc = $currentImg.attr('src');
        const $currentThumb = $list.find(`img[src$="${currentImgSrc}"]`).closest('li').index();
        const len = $list.find('li').length - 1;
        // let $nextImg;
        let nextImgIndex;

        if (direction === 'prev') {
            nextImgIndex = ($currentThumb === 0) ? len : $currentThumb - 1;
        } else {
            nextImgIndex = ($currentThumb === len) ? 0 : $currentThumb + 1;
        }

        const $nextImg = $list.find('li').eq(nextImgIndex).find('img').attr('src');
        $currentImg.fadeOut(speed, function() {
            $(this).attr('src', $nextImg).fadeIn(speed);
        });
    };

    const changeImage = function() {
        const img = $(this).attr('href');
        const $oldImg = $('div.elr-blackout img.img-visible');
        const oldImgSrc = $oldImg.attr('src');

        if (oldImgSrc !== img) {
            $oldImg.fadeOut(speed, function() {
                $(this).attr('src', img).fadeIn(speed);
            });
        }
    };

    const removeLightbox = function() {
        $('div.elr-blackout').fadeOut(speed, function() {
            $(this).remove();
        });
    };

    if ($images.length) {
        const thumbnails = createThumbnails($images);
        const $body = $('body');

        $images.on('click', 'a', function(e) {
            e.preventDefault();
            createLightbox.call(this, thumbnails, speed);
        });

        $body.on('click', 'div.elr-blackout button.close', removeLightbox);
        $body.on('click', 'div.elr-blackout', function(e) {
            e.stopPropagation();
            removeLightbox();
        });

        $body.on('click', 'div.elr-blackout ul.thumbnail-list a', function(e) {
            e.preventDefault();
            e.stopPropagation();
            changeImage.call(this);
        });

        elr.killEvent($body, 'click', 'div.elr-blackout .img-visible');
        elr.killEvent($body, 'click', 'div.elr-blackout .lightbox-nav button');

        $body.on('click', 'div.elr-blackout .lightbox-nav button', function(e) {
            e.preventDefault();
            e.stopPropagation();

            const direction = $(this).data('dir');

            advanceImage(direction);
        });

        $body.on('keydown', function(e) {
            if (e.which === 37) {
                advanceImage('prev');
            } else if (e.which === 39) {
                advanceImage('next');
            }
        });

        $body.on('keydown', function(e) {
            if (e.which === 27) {
                removeLightbox();
            }
        });
    }

    return self;
};

export default elrLightbox;<|endoftext|>


<commit_before>module.exports = function bridge(nativeWindow, win, unwrapEphemeral){
  function isObject(o){
    if (o == null) return o !== null && o !== undefined;
    return typeof o === 'object' || typeof o === 'function';
  }

  function encode(msg){
    if (msg == null)
      return '{}';
    else if (typeof msg === 'object')
      return JSON.stringify(msg);
    else if (typeof msg === 'string')
      return msg;
    else
      throw new TypeError("Tried to encode invalid type");
  }

  function decode(msg){
    try {
      return JSON.parse(msg);
    } catch (e) {
      return { error: e };
    }
  }

  var _call   = Function.prototype.call,
      _apply  = Function.prototype.apply,
      _bind   = Function.prototype.bind,
      _slice  = Array.prototype.slice,
      _hasOwn = Object.prototype.hasOwnProperty,
      char    = String.fromCharCode;

  var foreignObjects = new WeakMap,
      foreignIDs = new WeakMap,
      localObjects = new WeakMap,
      localIDs = new WeakMap,
      localCanonicals = [],
      foreignCanonicals = Object.create(null);

  var TOKEN       = char(1),
      LITERAL     = char(2),
      TRUE        = [TOKEN, 1],
      FALSE       = [TOKEN, 2],
      UNDEFINED   = [TOKEN, 3],
      NULL        = [TOKEN, 4],
      NAN         = [TOKEN, 5],
      INFINITY    = [TOKEN, 6],
      NEGINFINITY = [TOKEN, 7],
      NEGZERO     = [TOKEN, 8],
      ZERO        = [TOKEN, 9];

  var tokens = [, true, false, undefined, null, NaN, Infinity, -Infinity, -0, 0];

  var pipe = function(source, listeners){
    source.onmessage = function onmessage(msg){
      var res = {};
      msg = decode(msg);
      listeners[msg.type] && listeners[msg.type](msg.msg, res);
      return encode(res.result === undefined ? {} : res.result);
    };

    return {
      send: function send(type, msg){
        msg = { type: type, msg: msg };
        return decode(source.send(encode(msg)));
      },
      listen: function listen(type, handler){
        listeners[type] = handler;
      }
    };
  }(nativeWindow || appjs, {});

  if (!nativeWindow) {
    var LOCAL = char(15), FOREIGN = char(16);
    var logger = function logger(type, error){
      if (typeof node !== 'undefined') {
        logger = function logger(type, error){
          node.process.AppjsEmitter.emit('log', type, 'browser', error);
        };
        logger(type, context, error);
      }
    }
  } else {
    var LOCAL = char(16), FOREIGN = char(15);
    var logger = function logger(type, error){
      process.AppjsEmitter.emit('log', type, 'node', error);
    }
    nativeWindow.once('context-released', function released(){
      nativeWindow.onmessage = function(){ return ''; }
      unwrap = wrap = pipe.send = pipe.listen = function(){ return {} };
      mirror = {
        type      : function(){ return ['object'] },
        keys      : function(){ return [] },
        enumerate : function(){ return [] },
        props     : function(){ return [] },
        get       : function(){ return UNDEFINED },
        set       : function(){ return TRUE },
        proto     : function(){ return NULL },
        has       : function(){ return FALSE },
        hasOwn    : function(){ return FALSE },
        delete    : function(){ return TRUE },
        define    : function(){ return TRUE },
        describe  : function(){ return UNDEFINED },
        construct : function(){ return UNDEFINED },
        apply     : function(){ return UNDEFINED }
      };
      nativeWindow = foreignObjects = foreignIDs = localObjects = localIDs = localCanonicals = foreignCanonicals = null;
    });
  }

  wrap(nativeWindow ? global : window);

  function initForeign(obj, proxy){
    foreignObjects.set(proxy, obj);
    foreignIDs.set(obj, proxy);
    foreignCanonicals[obj[1]] = obj;
    return proxy;
  }

  function unwrap(obj){
    if (!isObject(obj)) {
      return obj;
    } else if (obj[0] === TOKEN) {
      return tokens[obj[1]];
    } else if (obj[0] === LITERAL) {
      return obj[1];
    } else if (obj[0] === FOREIGN) {
      if (obj[1] in foreignCanonicals) {
        return foreignIDs.get(foreignCanonicals[obj[1]]);
      } else {
        return initForeign(obj, new Mirror(obj));
      }
    } else if (obj[0] === LOCAL && localCanonicals[obj[1]]) {
      return localObjects.get(localCanonicals[obj[1]]);
    } else {
      return obj;
    }
  }

  function wrap(obj){
    if (!isObject(obj)) {
      switch (typeof obj) {
        case 'boolean':      return obj ? TRUE : FALSE;
        case 'undefined':    return UNDEFINED;
        case 'object':       return NULL;
        case 'string':       return [LITERAL, obj];
        case 'number':
          switch (obj) {
            case Infinity:   return INFINITY;
            case -Infinity:  return NEGINFINITY;
            case NaN:        return NAN;
            case 0:          return 1 / obj === -Infinity ? NEGZERO : ZERO;
            default:         return obj !== obj ? NAN : [LITERAL, obj];
          }
      }
    } else if (foreignObjects.has(obj)) {
      return foreignObjects.get(obj);
    } else if (localIDs.has(obj)) {
      return localIDs.get(obj);
    } else {
      var id = [LOCAL, localCanonicals.length];
      localObjects.set(id, obj);
      localIDs.set(obj, id);
      localCanonicals[id[1]] = id;
      return id;
    }
  }

  var mirror = {
    type: function type(obj){
      return [typeof obj];
    },
    keys: function keys(obj){
      return Object.keys(obj);
    },
    enumerate: function enumerate(obj){
      var i=0, k=[];
      for (k[i++] in obj);
      return k;
    },
    props: function props(obj){
      return Object.getOwnPropertyNames(obj);
    },
    get: function get(obj, key){
      return wrap(obj[key]);
    },
    proto: function proto(obj){
      return wrap(obj.__proto__);
    },
    has: function has(obj, key){
      return wrap(key in obj);
    },
    hasOwn: function hasOwn(obj, key){
      return wrap(_hasOwn.call(obj, key));
    },
    delete: function delete_(obj, key){
      delete obj[key];
      return TRUE;
    },
    define: function define(obj, key, desc){
      if ('value' in desc) {
        desc.value = unwrap(desc.value);
      } else {
        if (desc.get) desc.get = unwrap(desc.get);
        if (desc.set) desc.set = unwrap(desc.set);
      }
      Object.defineProperty(obj, key, desc);
      return TRUE;
    },
    describe: function describe(obj, key){
      var desc = Object.getOwnPropertyDescriptor(obj, key);
      if (desc) {
        desc.configurable = true;
        if ('value' in desc) {
          if (desc.value === undefined) desc.value = obj[key];
          desc.value = wrap(desc.value);
        } else {
          if (desc.get) desc.get = wrap(desc.get);
          if (desc.set) desc.set = wrap(desc.set);
        }
        return desc;
      } else if (desc === undefined && _hasOwn.call(obj, key)) {
        return { configurable: true,
                 enumerable: true,
                 writable: true,
                 value: wrap(obj[key]) };
      } else {
        return UNDEFINED;
      }
    },
    construct: function construct(obj, args){
      try {
        return wrap(new (_bind.apply(obj, [null].concat(args.map(unwrap)))));
      } catch (e) {
        logger('Constructor throw', e);
        return wrap(e);
      }
    },
  };

  if (nativeWindow) {
    mirror.apply = function apply(obj, receiver, args){
      try {
        return wrap(_apply.call(obj, unwrap(receiver), args.map(unwrap)));
      } catch (e) {
        logger('Apply throw', e);
        return wrap(e);
      }
    };
    mirror.set = function set(obj, key, value){
      obj[key] = unwrap(value);
      return TRUE;
    };
  } else {
    var proxyForProxy = function proxyForProxy(fn){
      return function(){ return _apply.call(fn, this, arguments) };
    };
    mirror.apply = function apply(obj, receiver, args){
      // workaround for bug where proxy functions are not valid DOM event handlers
      args = args.map(unwrap);
      if (obj.name === 'addEventListener' && typeof args[1] === 'function') {
        args[1] = proxyForProxy(args[1]);
      }
      try {
        return wrap(_apply.call(obj, unwrap(receiver), args));
      } catch (e) {
        logger('Apply throw', e);
        return wrap(e);
      }
    };
    mirror.set = function set(obj, key, value){
      value = unwrap(value);
      obj[key] = value;
      if (obj[key] === null && typeof value === 'function') {
        // workaround for bug where proxy functions are not valid DOM event handlers
        obj[key] = proxyForProxy(value);
      }
      return TRUE;
    };
  }

  function Mirror(obj){
    var self = this;
    var type = pipe.send('Δtype', obj)[0];
    this.id = obj;
    this.id2 = obj.concat(null);
    this.id3 = obj.concat(null, null);
    if (type === 'function') {
      return Proxy.createFunction(this,
        function(){ return self.apply(this, _slice.call(arguments)) },
        function(){ return self.construct(_slice.call(arguments)) }
      );
    } else {
      return Proxy.create(this, unwrap(pipe.send('Δproto', this.id)));
    }
  }

  Mirror.prototype = {
    keys: function keys(){
      return pipe.send('Δkeys', this.id);
    },
    enumerate: function enumerate(){
      return pipe.send('Δenumerate', this.id);
    },
    getOwnPropertyNames: function getOwnPropertyNames(){
      return pipe.send('Δprops', this.id);
    },
    get: function get(rcvr, key){
      this.id2[2] = key;
      return unwrap(pipe.send('Δget', this.id2));
    },
    set: function set(rcvr, key, value){
      this.id3[2] = key;
      this.id3[3] = wrap(value);
      pipe.send('Δset', this.id3);
      return true;
    },
    getOwnPropertyDescriptor: function getOwnPropertyDescriptor(key){
      this.id2[2] = key;
      var desc = pipe.send('Δdescribe', this.id2);
      if (desc) {
        desc.configurable = true;
        if ('value' in desc) {
          desc.value = unwrap(desc.value);
        } else {
          if (desc.get) desc.get = unwrap(desc.get);
          if (desc.set) desc.set = unwrap(desc.set);
        }
      }
      return desc;
    },
    has: function has(key){
      this.id2[2] = key;
      return pipe.send('Δhas', this.id2);
    },
    hasOwn: function hasOwn(key){
      this.id2[2] = key;
      return pipe.send('ΔhasOwn', this.id2);
    },
    delete: function delete_(key){
      this.id2[2] = key;
      pipe.send('Δdelete', this.id2);
      return true;
    },
    defineProperty: function defineProperty(key, desc){
      this.id3[2] = key;
      this.id3[3] = desc;
      if ('value' in desc) {
        desc.value = wrap(desc.value);
      } else {
        if (desc.get) desc.get = wrap(desc.get);
        if (desc.set) desc.set = wrap(desc.set);
      }
      pipe.send('Δdefine', this.id3);
      return true;
    },
    apply: function apply(receiver, args){
      this.id3[2] = wrap(receiver);
      this.id3[3] = args.map(wrap);
      return unwrap(pipe.send('Δapply', this.id3));
    },
    construct: function construct(args){
      this.id2[2] = args.map(wrap);
      return unwrap(pipe.send('Δconstruct', this.id2));
    }
  };

  Object.keys(mirror).forEach(function(key){
    pipe.listen('Δ'+key, function(val, res){
      res.result = mirror[key](unwrap(val), val[2], val[3]);
    });
  });

  if (nativeWindow) {
    void function(){
      var id = [FOREIGN, 0];
      unwrapEphemeral(win).morph(Mirror.prototype, {
        id:  id,
        id2: [FOREIGN, 0, null],
        id3: [FOREIGN, 0, null, null]
      });
      initForeign(id, win);
    }();
  } else {
    window.node = unwrap([FOREIGN, 0]);
  }
}
<commit_msg>fix the bridge logger to reflect removal of AppjsEmitter<commit_after>module.exports = function bridge(nativeWindow, win, unwrapEphemeral){
  function isObject(o){
    if (o == null) return o !== null && o !== undefined;
    return typeof o === 'object' || typeof o === 'function';
  }

  function encode(msg){
    if (msg == null)
      return '{}';
    else if (typeof msg === 'object')
      return JSON.stringify(msg);
    else if (typeof msg === 'string')
      return msg;
    else
      throw new TypeError("Tried to encode invalid type");
  }

  function decode(msg){
    try {
      return JSON.parse(msg);
    } catch (e) {
      return { error: e };
    }
  }

  var _call   = Function.prototype.call,
      _apply  = Function.prototype.apply,
      _bind   = Function.prototype.bind,
      _slice  = Array.prototype.slice,
      _hasOwn = Object.prototype.hasOwnProperty,
      char    = String.fromCharCode;

  var foreignObjects = new WeakMap,
      foreignIDs = new WeakMap,
      localObjects = new WeakMap,
      localIDs = new WeakMap,
      localCanonicals = [],
      foreignCanonicals = Object.create(null);

  var TOKEN       = char(1),
      LITERAL     = char(2),
      TRUE        = [TOKEN, 1],
      FALSE       = [TOKEN, 2],
      UNDEFINED   = [TOKEN, 3],
      NULL        = [TOKEN, 4],
      NAN         = [TOKEN, 5],
      INFINITY    = [TOKEN, 6],
      NEGINFINITY = [TOKEN, 7],
      NEGZERO     = [TOKEN, 8],
      ZERO        = [TOKEN, 9];

  var tokens = [, true, false, undefined, null, NaN, Infinity, -Infinity, -0, 0];

  var pipe = function(source, listeners){
    source.onmessage = function onmessage(msg){
      var res = {};
      msg = decode(msg);
      listeners[msg.type] && listeners[msg.type](msg.msg, res);
      return encode(res.result === undefined ? {} : res.result);
    };

    return {
      send: function send(type, msg){
        msg = { type: type, msg: msg };
        return decode(source.send(encode(msg)));
      },
      listen: function listen(type, handler){
        listeners[type] = handler;
      }
    };
  }(nativeWindow || appjs, {});

  if (!nativeWindow) {
    var LOCAL = char(15), FOREIGN = char(16);
    var logger = function logger(type, error){
      if (typeof node !== 'undefined') {
        logger = function logger(type, error){
          node.process.emit('appjs-log', type, 'browser', error);
        };
        logger(type, context, error);
      }
    }
  } else {
    var LOCAL = char(16), FOREIGN = char(15);
    var logger = function logger(type, error){
      process.emit('appjs-log', type, 'node', error);
    };
    nativeWindow.once('context-released', function released(){
      mirror = {
        type      : function(){ return ['object'] },
        keys      : function(){ return [] },
        enumerate : function(){ return [] },
        props     : function(){ return [] },
        get       : function(){ return UNDEFINED },
        set       : function(){ return TRUE },
        proto     : function(){ return NULL },
        has       : function(){ return FALSE },
        hasOwn    : function(){ return FALSE },
        delete    : function(){ return TRUE },
        define    : function(){ return TRUE },
        describe  : function(){ return UNDEFINED },
        construct : function(){ return UNDEFINED },
        apply     : function(){ return UNDEFINED }
      };
      unwrap = wrap = pipe.send = pipe.listen = function(){ return {} };
      nativeWindow.onmessage = function(){ return ''; }
      nativeWindow = null;
      foreignObjects = foreignIDs = foreignCanonicals = null;
      localObjects = localIDs = localCanonicals = null;
    });
  }

  wrap(nativeWindow ? global : window);

  function initForeign(obj, proxy){
    foreignObjects.set(proxy, obj);
    foreignIDs.set(obj, proxy);
    foreignCanonicals[obj[1]] = obj;
    return proxy;
  }

  function unwrap(obj){
    if (!isObject(obj)) {
      return obj;
    } else if (obj[0] === TOKEN) {
      return tokens[obj[1]];
    } else if (obj[0] === LITERAL) {
      return obj[1];
    } else if (obj[0] === FOREIGN) {
      if (obj[1] in foreignCanonicals) {
        return foreignIDs.get(foreignCanonicals[obj[1]]);
      } else {
        return initForeign(obj, new Mirror(obj));
      }
    } else if (obj[0] === LOCAL && localCanonicals[obj[1]]) {
      return localObjects.get(localCanonicals[obj[1]]);
    } else {
      return obj;
    }
  }

  function wrap(obj){
    if (!isObject(obj)) {
      switch (typeof obj) {
        case 'boolean':      return obj ? TRUE : FALSE;
        case 'undefined':    return UNDEFINED;
        case 'object':       return NULL;
        case 'string':       return [LITERAL, obj];
        case 'number':
          switch (obj) {
            case Infinity:   return INFINITY;
            case -Infinity:  return NEGINFINITY;
            case NaN:        return NAN;
            case 0:          return 1 / obj === -Infinity ? NEGZERO : ZERO;
            default:         return obj !== obj ? NAN : [LITERAL, obj];
          }
      }
    } else if (foreignObjects.has(obj)) {
      return foreignObjects.get(obj);
    } else if (localIDs.has(obj)) {
      return localIDs.get(obj);
    } else {
      var id = [LOCAL, localCanonicals.length];
      localObjects.set(id, obj);
      localIDs.set(obj, id);
      localCanonicals[id[1]] = id;
      return id;
    }
  }

  var mirror = {
    type: function type(obj){
      return [typeof obj];
    },
    keys: function keys(obj){
      return Object.keys(obj);
    },
    enumerate: function enumerate(obj){
      var i=0, k=[];
      for (k[i++] in obj);
      return k;
    },
    props: function props(obj){
      return Object.getOwnPropertyNames(obj);
    },
    get: function get(obj, key){
      return wrap(obj[key]);
    },
    proto: function proto(obj){
      return wrap(obj.__proto__);
    },
    has: function has(obj, key){
      return wrap(key in obj);
    },
    hasOwn: function hasOwn(obj, key){
      return wrap(_hasOwn.call(obj, key));
    },
    delete: function delete_(obj, key){
      delete obj[key];
      return TRUE;
    },
    define: function define(obj, key, desc){
      if ('value' in desc) {
        desc.value = unwrap(desc.value);
      } else {
        if (desc.get) desc.get = unwrap(desc.get);
        if (desc.set) desc.set = unwrap(desc.set);
      }
      Object.defineProperty(obj, key, desc);
      return TRUE;
    },
    describe: function describe(obj, key){
      var desc = Object.getOwnPropertyDescriptor(obj, key);
      if (desc) {
        desc.configurable = true;
        if ('value' in desc) {
          if (desc.value === undefined) desc.value = obj[key];
          desc.value = wrap(desc.value);
        } else {
          if (desc.get) desc.get = wrap(desc.get);
          if (desc.set) desc.set = wrap(desc.set);
        }
        return desc;
      } else if (desc === undefined && _hasOwn.call(obj, key)) {
        return { configurable: true,
                 enumerable: true,
                 writable: true,
                 value: wrap(obj[key]) };
      } else {
        return UNDEFINED;
      }
    },
    construct: function construct(obj, args){
      try {
        return wrap(new (_bind.apply(obj, [null].concat(args.map(unwrap)))));
      } catch (e) {
        logger('Constructor throw', e);
        return wrap(e);
      }
    },
  };

  if (nativeWindow) {
    mirror.apply = function apply(obj, receiver, args){
      try {
        return wrap(_apply.call(obj, unwrap(receiver), args.map(unwrap)));
      } catch (e) {
        logger('Apply throw', e);
        return wrap(e);
      }
    };
    mirror.set = function set(obj, key, value){
      obj[key] = unwrap(value);
      return TRUE;
    };
  } else {
    var proxyForProxy = function proxyForProxy(fn){
      return function(){ return _apply.call(fn, this, arguments) };
    };
    mirror.apply = function apply(obj, receiver, args){
      // workaround for bug where proxy functions are not valid DOM event handlers
      args = args.map(unwrap);
      if (obj.name === 'addEventListener' && typeof args[1] === 'function') {
        args[1] = proxyForProxy(args[1]);
      }
      try {
        return wrap(_apply.call(obj, unwrap(receiver), args));
      } catch (e) {
        logger('Apply throw', e);
        return wrap(e);
      }
    };
    mirror.set = function set(obj, key, value){
      value = unwrap(value);
      obj[key] = value;
      if (obj[key] === null && typeof value === 'function') {
        // workaround for bug where proxy functions are not valid DOM event handlers
        obj[key] = proxyForProxy(value);
      }
      return TRUE;
    };
  }

  function Mirror(obj){
    var self = this;
    var type = pipe.send('Δtype', obj)[0];
    this.id = obj;
    this.id2 = obj.concat(null);
    this.id3 = obj.concat(null, null);
    if (type === 'function') {
      return Proxy.createFunction(this,
        function(){ return self.apply(this, _slice.call(arguments)) },
        function(){ return self.construct(_slice.call(arguments)) }
      );
    } else {
      return Proxy.create(this, unwrap(pipe.send('Δproto', this.id)));
    }
  }

  Mirror.prototype = {
    keys: function keys(){
      return pipe.send('Δkeys', this.id);
    },
    enumerate: function enumerate(){
      return pipe.send('Δenumerate', this.id);
    },
    getOwnPropertyNames: function getOwnPropertyNames(){
      return pipe.send('Δprops', this.id);
    },
    get: function get(rcvr, key){
      this.id2[2] = key;
      return unwrap(pipe.send('Δget', this.id2));
    },
    set: function set(rcvr, key, value){
      this.id3[2] = key;
      this.id3[3] = wrap(value);
      pipe.send('Δset', this.id3);
      return true;
    },
    getOwnPropertyDescriptor: function getOwnPropertyDescriptor(key){
      this.id2[2] = key;
      var desc = pipe.send('Δdescribe', this.id2);
      if (desc) {
        desc.configurable = true;
        if ('value' in desc) {
          desc.value = unwrap(desc.value);
        } else {
          if (desc.get) desc.get = unwrap(desc.get);
          if (desc.set) desc.set = unwrap(desc.set);
        }
      }
      return desc;
    },
    has: function has(key){
      this.id2[2] = key;
      return pipe.send('Δhas', this.id2);
    },
    hasOwn: function hasOwn(key){
      this.id2[2] = key;
      return pipe.send('ΔhasOwn', this.id2);
    },
    delete: function delete_(key){
      this.id2[2] = key;
      pipe.send('Δdelete', this.id2);
      return true;
    },
    defineProperty: function defineProperty(key, desc){
      this.id3[2] = key;
      this.id3[3] = desc;
      if ('value' in desc) {
        desc.value = wrap(desc.value);
      } else {
        if (desc.get) desc.get = wrap(desc.get);
        if (desc.set) desc.set = wrap(desc.set);
      }
      pipe.send('Δdefine', this.id3);
      return true;
    },
    apply: function apply(receiver, args){
      this.id3[2] = wrap(receiver);
      this.id3[3] = args.map(wrap);
      return unwrap(pipe.send('Δapply', this.id3));
    },
    construct: function construct(args){
      this.id2[2] = args.map(wrap);
      return unwrap(pipe.send('Δconstruct', this.id2));
    }
  };

  Object.keys(mirror).forEach(function(key){
    pipe.listen('Δ'+key, function(val, res){
      res.result = mirror[key](unwrap(val), val[2], val[3]);
    });
  });

  if (nativeWindow) {
    void function(){
      var id = [FOREIGN, 0];
      unwrapEphemeral(win).morph(Mirror.prototype, {
        id:  id,
        id2: [FOREIGN, 0, null],
        id3: [FOREIGN, 0, null, null]
      });
      initForeign(id, win);
    }();
  } else {
    window.node = unwrap([FOREIGN, 0]);
  }
}
<|endoftext|>


<commit_before>describe("About Arrays", function() {

  //We shall contemplate truth by testing reality, via spec expectations.
  it("should create arrays", function() {
    var emptyArray = [];
    expect(typeof(emptyArray)).toBe(FILL_ME_IN); //A mistake? - http:javascript.crockford.com/remedial.html
    expect(emptyArray.length).toBe(FILL_ME_IN);

    var multiTypeArray = [0, 1, "two", function () { return 3; }, {value1: 4, value2: 5}, [6, 7]];
    expect(multiTypeArray[0]).toBe(FILL_ME_IN);
    expect(multiTypeArray[2]).toBe(FILL_ME_IN);
    expect(multiTypeArray[3]()).toBe(FILL_ME_IN);
    expect(multiTypeArray[4].value1).toBe(FILL_ME_IN);
    expect(multiTypeArray[4]["value2"]).toBe(FILL_ME_IN);
    expect(multiTypeArray[5][0]).toBe(FILL_ME_IN);
  });

  it("should understand array literals", function () {
    var array = [];
    expect(array).toEqual([]);

    array[0] = 1;
    expect(array).toEqual([1]);

    array[1] = 2;
    expect(array).toEqual([1, FILL_ME_IN]);

    array.push(3);
    expect(array).toEqual(FILL_ME_IN);
  });

  it("should understand array length", function () {
    var fourNumberArray = [1, 2, 3, 4];

    expect(fourNumberArray.length).toBe(FILL_ME_IN);
    fourNumberArray.push(5, 6);
    expect(fourNumberArray.length).toBe(FILL_ME_IN);

    var tenEmptyElementArray = new Array(10);
    expect(tenEmptyElementArray.length).toBe(FILL_ME_IN);

    tenEmptyElementArray.length = 5;
    expect(tenEmptyElementArray.length).toBe(FILL_ME_IN);
  });

  it("should slice arrays", function () {
    var array = ["peanut", "butter", "and", "jelly"];

    expect(array.slice(0, 1)).toEqual(FILL_ME_IN);
    expect(array.slice(0, 2)).toEqual(FILL_ME_IN);
    expect(array.slice(2, 2)).toEqual(FILL_ME_IN);
    expect(array.slice(2, 20)).toEqual(FILL_ME_IN);
    expect(array.slice(3, 0)).toEqual(FILL_ME_IN);
    expect(array.slice(3, 100)).toEqual(FILL_ME_IN);
    expect(array.slice(5, 1)).toEqual(FILL_ME_IN);
  });

  it("should know array references", function () {
    var array = [ "zero", "one", "two", "three", "four", "five" ];

    function passedByReference(refArray) {
      refArray[1] = "changed in function";
    }
    passedByReference(array);
    expect(array[1]).toBe(FILL_ME_IN);

    var assignedArray = array;
    assignedArray[5] = "changed in assignedArray";
    expect(array[5]).toBe(FILL_ME_IN);

    var copyOfArray = array.slice();
    copyOfArray[3] = "changed in copyOfArray";
    expect(array[3]).toBe(FILL_ME_IN);
  });

  it("should push and pop", function () {
    var array = [1, 2];
    array.push(3);

    expect(array).toEqual(FILL_ME_IN);

    var poppedValue = array.pop();
    expect(poppedValue).toBe(FILL_ME_IN);
    expect(array).toEqual(FILL_ME_IN);
  });

  it("should know about shifting arrays", function () {
    var array = [1, 2];

    array.unshift(3);
    expect(array).toEqual(FILL_ME_IN);

    var shiftedValue = array.shift();
    expect(shiftedValue).toEqual(FILL_ME_IN);
    expect(array).toEqual(FILL_ME_IN);
  });
});
<commit_msg>Made Arrays tests pass  Please enter the commit message for your changes. Lines starting<commit_after>describe("About Arrays", function() {

  //We shall contemplate truth by testing reality, via spec expectations.
  it("should create arrays", function() {
    var emptyArray = [];
    expect(typeof(emptyArray)).toBe("object"); //A mistake? - http:javascript.crockford.com/remedial.html
    expect(emptyArray.length).toBe(0);

    var multiTypeArray = [0, 1, "two", function () { return 3; }, {value1: 4, value2: 5}, [6, 7]];
    expect(multiTypeArray[0]).toBe(0);
    expect(multiTypeArray[2]).toBe("two");
    expect(multiTypeArray[3]()).toBe(3);
    expect(multiTypeArray[4].value1).toBe(4);
    expect(multiTypeArray[4]["value2"]).toBe(5);
    expect(multiTypeArray[5][0]).toBe(6);
  });

  it("should understand array literals", function () {
    var array = [];
    expect(array).toEqual([]);

    array[0] = 1;
    expect(array).toEqual([1]);

    array[1] = 2;
    expect(array).toEqual([1, 2]);

    array.push(3);
    expect(array).toEqual([1, 2, 3]);
  });

  it("should understand array length", function () {
    var fourNumberArray = [1, 2, 3, 4];

    expect(fourNumberArray.length).toBe(4);
    fourNumberArray.push(5, 6);
    expect(fourNumberArray.length).toBe(6);

    var tenEmptyElementArray = new Array(10);
    expect(tenEmptyElementArray.length).toBe(10);

    tenEmptyElementArray.length = 5;
    expect(tenEmptyElementArray.length).toBe(5);
  });

  it("should slice arrays", function () {
    var array = ["peanut", "butter", "and", "jelly"];

    expect(array.slice(0, 1)).toEqual(["peanut"]);
    expect(array.slice(0, 2)).toEqual(["peanut", "butter"]);
    expect(array.slice(2, 2)).toEqual([]);
    expect(array.slice(2, 20)).toEqual(["and", "jelly"]);
    expect(array.slice(3, 0)).toEqual([]);
    expect(array.slice(3, 100)).toEqual(["jelly"]);
    expect(array.slice(5, 1)).toEqual([]);
  });

  it("should know array references", function () {
    var array = [ "zero", "one", "two", "three", "four", "five" ];

    function passedByReference(refArray) {
      refArray[1] = "changed in function";
    }
    passedByReference(array);
    expect(array[1]).toBe("changed in function");

    var assignedArray = array;
    assignedArray[5] = "changed in assignedArray";
    expect(array[5]).toBe("changed in assignedArray");

    var copyOfArray = array.slice();
    copyOfArray[3] = "changed in copyOfArray";
    expect(array[3]).toBe("three");
  });

  it("should push and pop", function () {
    var array = [1, 2];
    array.push(3);

    expect(array).toEqual([1, 2, 3]);

    var poppedValue = array.pop();
    expect(poppedValue).toBe(3);
    expect(array).toEqual([1, 2]);
  });

  it("should know about shifting arrays", function () {
    var array = [1, 2];

    array.unshift(3);
    expect(array).toEqual([3, 1, 2]);

    var shiftedValue = array.shift();
    expect(shiftedValue).toEqual(3);
    expect(array).toEqual([1, 2]);
  });
});
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react'
import Word from './Word'

export default class WordList extends Component {

    render() {
        const style = {
            background: '#0cc3ff'
        };
        return (

                    {
                        this.props.wordList.map((word, index)=>
                            <Word key={word.word+index} {...word}/>)
                    }

        )
    }
};<commit_msg>WordList container still has the same height, even if it does not hold 10 words<commit_after>import React, { Component, PropTypes } from 'react'
import Word from './Word'

export default class WordList extends Component {

    padRows(numberOfWords) {
        let divs = [];
        while (numberOfWords < 10) {
            divs.push(

);
            numberOfWords++;
        }
        return divs;
    }

    render() {
        const style = {
            background: '#0cc3ff'
        };
        return (

                    {
                        this.props.wordList.map((word, index)=>
                            <Word key={word.word+index} {...word}/>)
                    }
                    {this.padRows(this.props.wordList.length)}

        )
    }
};<|endoftext|>


<commit_before>describe("About Arrays", function() {

  //We shall contemplate truth by testing reality, via spec expectations.
  it("should create arrays", function() {
    var emptyArray = [];
    expect(typeof(emptyArray)).toBe(FILL_ME_IN); //A mistake? - http:javascript.crockford.com/remedial.html
    expect(emptyArray.length).toBe(FILL_ME_IN);

    var multiTypeArray = [0, 1, "two", function () { return 3; }, {value1: 4, value2: 5}, [6, 7]];
    expect(multiTypeArray[0]).toBe(FILL_ME_IN);
    expect(multiTypeArray[2]).toBe(FILL_ME_IN);
    expect(multiTypeArray[3]()).toBe(FILL_ME_IN);
    expect(multiTypeArray[4].value1).toBe(FILL_ME_IN);
    expect(multiTypeArray[4]["value2"]).toBe(FILL_ME_IN);
    expect(multiTypeArray[5][0]).toBe(FILL_ME_IN);
  });

  it("should understand array literals", function () {
    var array = [];
    expect(array).toEqual([]);

    array[0] = 1;
    expect(array).toEqual([1]);

    array[1] = 2;
    expect(array).toEqual([1, FILL_ME_IN]);

    array.push(3);
    expect(array).toEqual(FILL_ME_IN);
  });

  it("should understand array length", function () {
    var fourNumberArray = [1, 2, 3, 4];

    expect(fourNumberArray.length).toBe(FILL_ME_IN);
    fourNumberArray.push(5, 6);
    expect(fourNumberArray.length).toBe(FILL_ME_IN);

    var tenEmptyElementArray = new Array(10);
    expect(tenEmptyElementArray.length).toBe(FILL_ME_IN);

    tenEmptyElementArray.length = 5;
    expect(tenEmptyElementArray.length).toBe(FILL_ME_IN);
  });

  it("should slice arrays", function () {
    var array = ["peanut", "butter", "and", "jelly"];

    expect(array.slice(0, 1)).toEqual(FILL_ME_IN);
    expect(array.slice(0, 2)).toEqual(FILL_ME_IN);
    expect(array.slice(2, 2)).toEqual(FILL_ME_IN);
    expect(array.slice(2, 20)).toEqual(FILL_ME_IN);
    expect(array.slice(3, 0)).toEqual(FILL_ME_IN);
    expect(array.slice(3, 100)).toEqual(FILL_ME_IN);
    expect(array.slice(5, 1)).toEqual(FILL_ME_IN);
  });

  it("should know array references", function () {
    var array = [ "zero", "one", "two", "three", "four", "five" ];

    function passedByReference(refArray) {
      refArray[1] = "changed in function";
    }
    passedByReference(array);
    expect(array[1]).toBe(FILL_ME_IN);

    var assignedArray = array;
    assignedArray[5] = "changed in assignedArray";
    expect(array[5]).toBe(FILL_ME_IN);

    var copyOfArray = array.slice();
    copyOfArray[3] = "changed in copyOfArray";
    expect(array[3]).toBe(FILL_ME_IN);
  });

  it("should push and pop", function () {
    var array = [1, 2];
    array.push(3);

    expect(array).toEqual(FILL_ME_IN);

    var poppedValue = array.pop();
    expect(poppedValue).toBe(FILL_ME_IN);
    expect(array).toEqual(FILL_ME_IN);
  });

  it("should know about shifting arrays", function () {
    var array = [1, 2];

    array.unshift(3);
    expect(array).toEqual(FILL_ME_IN);

    var shiftedValue = array.shift();
    expect(shiftedValue).toEqual(FILL_ME_IN);
    expect(array).toEqual(FILL_ME_IN);
  });
});
<commit_msg>Update AboutArrays.js<commit_after>describe("About Arrays", function() {

  //We shall contemplate truth by testing reality, via spec expectations.
  it("should create arrays", function() {
    var emptyArray = [];
    expect(typeof(emptyArray)).toBe('object'); //A mistake? - http:javascript.crockford.com/remedial.html
    expect(emptyArray.length).toBe(0);

    var multiTypeArray = [0, 1, "two", function () { return 3; }, {value1: 4, value2: 5}, [6, 7]];
    expect(multiTypeArray[0]).toBe(0);
    expect(multiTypeArray[2]).toBe("two");
    expect(multiTypeArray[3]()).toBe(3);
    expect(multiTypeArray[4].value1).toBe(4);
    expect(multiTypeArray[4]["value2"]).toBe(5);
    expect(multiTypeArray[5][0]).toBe(6);
  });

  it("should understand array literals", function () {
    var array = [];
    expect(array).toEqual([]);

    array[0] = 1;
    expect(array).toEqual([1]);

    array[1] = 2;
    expect(array).toEqual([1, 2]);

    array.push(3);
    expect(array).toEqual([1,2,3]);
  });

  it("should understand array length", function () {
    var fourNumberArray = [1, 2, 3, 4];

    expect(fourNumberArray.length).toBe(4);
    fourNumberArray.push(5, 6);
    expect(fourNumberArray.length).toBe(6);

    var tenEmptyElementArray = new Array(10);
    expect(tenEmptyElementArray.length).toBe(10);

    tenEmptyElementArray.length = 5;
    expect(tenEmptyElementArray.length).toBe(5);
  });

  it("should slice arrays", function () {
    var array = ["peanut", "butter", "and", "jelly"];

    expect(array.slice(0, 1)).toEqual(["peanut"]);
    expect(array.slice(0, 2)).toEqual(["peanut", "butter"]);
    expect(array.slice(2, 2)).toEqual([]);
    expect(array.slice(2, 20)).toEqual(["and","jelly"]);
    expect(array.slice(3, 0)).toEqual([]);
    expect(array.slice(3, 100)).toEqual(["jelly"]);
    expect(array.slice(5, 1)).toEqual([]);
  });

  it("should know array references", function () {
    var array = [ "zero", "one", "two", "three", "four", "five" ];

    function passedByReference(refArray) {
      refArray[1] = "changed in function";
    }
    passedByReference(array);
    expect(array[1]).toBe("changed in function");

    var assignedArray = array;
    assignedArray[5] = "changed in assignedArray";
    expect(array[5]).toBe("changed in assignedArray");

    var copyOfArray = array.slice();
    copyOfArray[3] = "changed in copyOfArray";
    expect(array[3]).toBe("three");
  });

  it("should push and pop", function () {
    var array = [1, 2];
    array.push(3);

    expect(array).toEqual([1,2,3]);

    var poppedValue = array.pop();
    expect(poppedValue).toBe(3);
    expect(array).toEqual([1,2]);
  });

  it("should know about shifting arrays", function () {
    var array = [1, 2];

    array.unshift(3);
    expect(array).toEqual([3,1,2]);

    var shiftedValue = array.shift();
    expect(shiftedValue).toEqual(3);
    expect(array).toEqual([1,2]);
  });
});
<|endoftext|>


<commit_before>const helper = require('think-helper');
const assert = require('assert');
const cookies = require('cookies');
const url = require('url');

const PARAM = Symbol('context-param');
const POST = Symbol('context-post');
const FILE = Symbol('context-file');

/**
 * extend context
 */
module.exports = {
  /**
   * get userAgent header
   */
  get userAgent(){
    return this.header['user-agent'];
  },
  /**
   * get referer header
   */
  referer(onlyHost){
    return this.referrer(onlyHost);
  },
  /**
   * get referer header
   */
  referrer(onlyHost){
    let referrer = this.header['referer'];
    if(!referrer || !onlyHost) return referrer;
    return url.parse(referrer).hostname;
  },
  /**
   * is get request
   */
  get isGet(){
    return this.method === 'GET';
  },
  /**
   * is post request
   */
  get isPost(){
    return this.method === 'POST';
  },
  /**
   * is method
   */
  isMethod(method){
    return this.method === method.toUpperCase();
  },
  /**
   * is command line invoke
   */
  get isCli(){
    return think.isCli;
  },
  /**
   * is ajax request
   */
  isAjax(method){
    if(method && !this.isMethod(method)) return false;
    return this.header['x-requested-with'] === 'XMLHttpRequest';
  },
  /**
   * is jsonp request
   */
  isJsonp(callbackField = this.config('jsonpCallbackField')){
    return !!this.param(callbackField);
  },
  /**
   * send jsonp data
   */
  jsonp(data, callbackField = this.config('jsonpCallbackField')){
    let field = this.param(callbackField);
    //remove unsafe chars
    field = (field || '').replace(/[^\w\.]/g, '');
    if(field){
      data = `${field}(${JSON.stringify(data)})`;
    }
    this.type = this.config('jsonContentType');
    this.body = data;
    return false;
  },
  /**
   * send json data
   */
  json(data){
    this.type = this.config('jsonContentType');
    this.body = data;
    return false;
  },
  /**
   * send success data
   */
  success(data = '', message = ''){
    const obj = {
      [this.config('errnoField')]: 0,
      [this.config('errmsgField')]: message,
      data
    };
    this.type = this.config('jsonContentType');
    this.body = obj;
    return false;
  },
  /**
   * send fail data
   */
  fail(errno, errmsg = '', data = ''){
    let obj;
    if(helper.isObject(errno)){
      obj = errno;
    }else{
      if(/^[A-Z\_]+$/.test(errno)){
        const messages = think.app.validators.messages || {};
        const msg = messages[errno];
        if(think.isArray(msg)){
          [errno, errmsg] = msg;
        }
      }
      if (!think.isNumber(errno)) {
        [data, errmsg, errno] = [errmsg, errno, this.config('defaultErrno')]
      }
      obj = {
        [this.config('errnoField')]: errno,
        [this.config('errmsgField')]: errmsg
      };
      if(data){
        obj.data = data;
      }
    }
    this.type = this.config('jsonContentType');
    this.body = obj;
    return false;
  },
  /**
   * set expires header
   */
  expires(time){
    time = helper.ms(time);
    const date = new Date(Date.now() + time);
    this.set('Cache-Control', `max-age=${time}`);
    this.set('Expires', date.toUTCString());
  },
  /**
   * get or set configs
   * @param {String} name
   * @param {Mixed} value
   * @param {String} m
   */
  config(name, value, m = this.module) {
    return think.config(name, value, m);
  },
  /**
   * get or set query data
   * `query` or `get` is already used in koa
   * @param {String} name
   * @param {Mixed} value
   */
  param(name, value) {
    if(!this[PARAM]){
      this[PARAM] = Object.assign({}, this.query);
    }
    if(!name) return this[PARAM];
    if(helper.isObject(name)){
      this[PARAM] = Object.assign(this[PARAM], name);
      return this;
    }
    assert(name && helper.isString(name), 'param.name must be a string');
    if(value === undefined){
      // this.param('a,b')
      if(name.indexOf(',') > -1){
        let value = {};
        name.split(',').forEach(item => {
          value[item] = this[PARAM][item];
        });
        return value;
      }
      return this[PARAM][name];
    }
    this[PARAM][name] = value;
    return this;
  },
  /**
   * get or set post data
   * @param {String} name
   * @param {Mixed} value
   */
  post(name, value){
    if(!this[POST]){
      this[POST] = Object.assign({}, this.request.body && this.request.body.post);
    }
    if(!name) return this[POST];
    if(helper.isObject(name)){
      this[POST] = Object.assign(this[POST], name);
      return this;
    }
    if(value === undefined){
      // this.param('a,b')
      if(name.indexOf(',') > -1){
        let value = {};
        name.split(',').forEach(item => {
          value[item] = this[POST][item];
        });
        return value;
      }
      return this[POST][name];
    }
    this[POST][name] = value;
    return this;
  },
  /**
   * get or set file data
   * @param {String} name
   * @param {Mixed} value
   */
  file(name, value){
    if(!this[FILE]){
      this[FILE] = Object.assign({}, this.request.body && this.request.body.file);
    }
    if(!name) return this[FILE];
    if(helper.isObject(name)){
      this[FILE] = Object.assign(this[FILE], name);
      return this;
    }
    if(value === undefined){
      return this[FILE][name];
    }
    this[FILE][name] = value;
    return this;
  },
  /**
   * get or set cookie
   * @param {String} name
   * @param {String} value
   * @param {Object} options
   */
  cookie(name, value, options = {}){
    assert(name && helper.isString(name), 'cookie.name must be a string');
    options = Object.assign({}, this.config('cookie'), options);
    const instance = new cookies(this.req, this.res, {
      keys: options.keys,
      secure: this.req.secure
    });
    //get cookie
    if(value === undefined){
      return instance.get(name, options);
    }
    //remove cookie
    if(value === null){
      return instance.set(name, '', {
        maxAge: -1
      });
    }
    assert(helper.isString(value), 'cookie value must be a string');
    //http://browsercookielimits.squawky.net/
    if(value.length >= 4094){
      this.app.emit('cookieLimit', {name, value, ctx: this});
    }
    //set cookie
    return instance.set(name, value, options);
  },
  /**
   * get controller instance
   * @param {String} name
   * @param {String} m
   */
  controller(name, m){
    return think.controller(name, this, m);
  },
  /**
   * get service
   * @param {String} name
   * @param {String} m
   */
  service(name, m){
    return think.service(name, m);
  }
}
<commit_msg>Fix remove cookie not support domain<commit_after>const helper = require('think-helper');
const assert = require('assert');
const cookies = require('cookies');
const url = require('url');

const PARAM = Symbol('context-param');
const POST = Symbol('context-post');
const FILE = Symbol('context-file');

/**
 * extend context
 */
module.exports = {
  /**
   * get userAgent header
   */
  get userAgent(){
    return this.header['user-agent'];
  },
  /**
   * get referer header
   */
  referer(onlyHost){
    return this.referrer(onlyHost);
  },
  /**
   * get referer header
   */
  referrer(onlyHost){
    let referrer = this.header['referer'];
    if(!referrer || !onlyHost) return referrer;
    return url.parse(referrer).hostname;
  },
  /**
   * is get request
   */
  get isGet(){
    return this.method === 'GET';
  },
  /**
   * is post request
   */
  get isPost(){
    return this.method === 'POST';
  },
  /**
   * is method
   */
  isMethod(method){
    return this.method === method.toUpperCase();
  },
  /**
   * is command line invoke
   */
  get isCli(){
    return think.isCli;
  },
  /**
   * is ajax request
   */
  isAjax(method){
    if(method && !this.isMethod(method)) return false;
    return this.header['x-requested-with'] === 'XMLHttpRequest';
  },
  /**
   * is jsonp request
   */
  isJsonp(callbackField = this.config('jsonpCallbackField')){
    return !!this.param(callbackField);
  },
  /**
   * send jsonp data
   */
  jsonp(data, callbackField = this.config('jsonpCallbackField')){
    let field = this.param(callbackField);
    //remove unsafe chars
    field = (field || '').replace(/[^\w\.]/g, '');
    if(field){
      data = `${field}(${JSON.stringify(data)})`;
    }
    this.type = this.config('jsonContentType');
    this.body = data;
    return false;
  },
  /**
   * send json data
   */
  json(data){
    this.type = this.config('jsonContentType');
    this.body = data;
    return false;
  },
  /**
   * send success data
   */
  success(data = '', message = ''){
    const obj = {
      [this.config('errnoField')]: 0,
      [this.config('errmsgField')]: message,
      data
    };
    this.type = this.config('jsonContentType');
    this.body = obj;
    return false;
  },
  /**
   * send fail data
   */
  fail(errno, errmsg = '', data = ''){
    let obj;
    if(helper.isObject(errno)){
      obj = errno;
    }else{
      if(/^[A-Z\_]+$/.test(errno)){
        const messages = think.app.validators.messages || {};
        const msg = messages[errno];
        if(think.isArray(msg)){
          [errno, errmsg] = msg;
        }
      }
      if (!think.isNumber(errno)) {
        [data, errmsg, errno] = [errmsg, errno, this.config('defaultErrno')]
      }
      obj = {
        [this.config('errnoField')]: errno,
        [this.config('errmsgField')]: errmsg
      };
      if(data){
        obj.data = data;
      }
    }
    this.type = this.config('jsonContentType');
    this.body = obj;
    return false;
  },
  /**
   * set expires header
   */
  expires(time){
    time = helper.ms(time);
    const date = new Date(Date.now() + time);
    this.set('Cache-Control', `max-age=${time}`);
    this.set('Expires', date.toUTCString());
  },
  /**
   * get or set configs
   * @param {String} name
   * @param {Mixed} value
   * @param {String} m
   */
  config(name, value, m = this.module) {
    return think.config(name, value, m);
  },
  /**
   * get or set query data
   * `query` or `get` is already used in koa
   * @param {String} name
   * @param {Mixed} value
   */
  param(name, value) {
    if(!this[PARAM]){
      this[PARAM] = Object.assign({}, this.query);
    }
    if(!name) return this[PARAM];
    if(helper.isObject(name)){
      this[PARAM] = Object.assign(this[PARAM], name);
      return this;
    }
    assert(name && helper.isString(name), 'param.name must be a string');
    if(value === undefined){
      // this.param('a,b')
      if(name.indexOf(',') > -1){
        let value = {};
        name.split(',').forEach(item => {
          value[item] = this[PARAM][item];
        });
        return value;
      }
      return this[PARAM][name];
    }
    this[PARAM][name] = value;
    return this;
  },
  /**
   * get or set post data
   * @param {String} name
   * @param {Mixed} value
   */
  post(name, value){
    if(!this[POST]){
      this[POST] = Object.assign({}, this.request.body && this.request.body.post);
    }
    if(!name) return this[POST];
    if(helper.isObject(name)){
      this[POST] = Object.assign(this[POST], name);
      return this;
    }
    if(value === undefined){
      // this.param('a,b')
      if(name.indexOf(',') > -1){
        let value = {};
        name.split(',').forEach(item => {
          value[item] = this[POST][item];
        });
        return value;
      }
      return this[POST][name];
    }
    this[POST][name] = value;
    return this;
  },
  /**
   * get or set file data
   * @param {String} name
   * @param {Mixed} value
   */
  file(name, value){
    if(!this[FILE]){
      this[FILE] = Object.assign({}, this.request.body && this.request.body.file);
    }
    if(!name) return this[FILE];
    if(helper.isObject(name)){
      this[FILE] = Object.assign(this[FILE], name);
      return this;
    }
    if(value === undefined){
      return this[FILE][name];
    }
    this[FILE][name] = value;
    return this;
  },
  /**
   * get or set cookie
   * @param {String} name
   * @param {String} value
   * @param {Object} options
   */
  cookie(name, value, options = {}){
    assert(name && helper.isString(name), 'cookie.name must be a string');
    options = Object.assign({}, this.config('cookie'), options);
    const instance = new cookies(this.req, this.res, {
      keys: options.keys,
      secure: this.req.secure
    });
    //get cookie
    if(value === undefined){
      return instance.get(name, options);
    }
    //remove cookie
    if(value === null){
      options.maxAge = -1;
      return instance.set(name, '', options);
    }
    assert(helper.isString(value), 'cookie value must be a string');
    //http://browsercookielimits.squawky.net/
    if(value.length >= 4094){
      this.app.emit('cookieLimit', {name, value, ctx: this});
    }
    //set cookie
    return instance.set(name, value, options);
  },
  /**
   * get controller instance
   * @param {String} name
   * @param {String} m
   */
  controller(name, m){
    return think.controller(name, this, m);
  },
  /**
   * get service
   * @param {String} name
   * @param {String} m
   */
  service(name, m){
    return think.service(name, m);
  }
}
<|endoftext|>


<commit_before>describe("About Arrays", function() {

  // We shall contemplate truth by testing reality, via spec expectations.
  it("should create arrays", function() {
    var emptyArray = [];
    expect(typeof(emptyArray)).toBe(FILL_ME_IN); // A mistake?-- http:javascript.crockford.com/remedial.html
    expect(emptyArray.length).toBe(FILL_ME_IN);

    var multiTypeArray = [0, 1, "two", function() { return 3; }, {value1: 4, value2: 5}, [6, 7]];
    expect(multiTypeArray[0]).toBe(FILL_ME_IN);
    expect(multiTypeArray[2]).toBe(FILL_ME_IN);
    expect(multiTypeArray[3]()).toBe(FILL_ME_IN);
    expect(multiTypeArray[4].value1).toBe(FILL_ME_IN);
    expect(multiTypeArray[4]["value2"]).toBe(FILL_ME_IN);
    expect(multiTypeArray[5][0]).toBe(FILL_ME_IN);
  });

  it("should understand array literals", function() {
    var array = [];
    expect(array).toEqual([]);

    array[0] = 1;
    expect(array).toEqual([1]);

    array[1] = 2;
    expect(array).toEqual([1, FILL_ME_IN]);

    array.push(3);
    expect(array).toEqual(FILL_ME_IN);
  });

  it("should understand array length", function() {
    var fourNumberArray = [1, 2, 3, 4];

    expect(fourNumberArray.length).toBe(FILL_ME_IN);
    fourNumberArray.push(5, 6);
    expect(fourNumberArray.length).toBe(FILL_ME_IN);

    var tenEmptyElementArray = new Array(10);
    expect(tenEmptyElementArray.length).toBe(FILL_ME_IN);

    tenEmptyElementArray.length = 5;
    expect(tenEmptyElementArray.length).toBe(FILL_ME_IN);
  });

  it("should slice arrays", function() {
    var array = ["peanut", "butter", "and", "jelly"];

    expect(array.slice(0, 1)).toEqual(FILL_ME_IN);
    expect(array.slice(0, 2)).toEqual(FILL_ME_IN);
    expect(array.slice(2, 2)).toEqual(FILL_ME_IN);
    expect(array.slice(2, 20)).toEqual(FILL_ME_IN);
    expect(array.slice(3, 0)).toEqual(FILL_ME_IN);
    expect(array.slice(3, 100)).toEqual(FILL_ME_IN);
    expect(array.slice(5, 1)).toEqual(FILL_ME_IN);
  });

  it("should know array references", function() {
    var array = [ "zero", "one", "two", "three", "four", "five" ];

    function passedByReference(refArray) {
      refArray[1] = "changed in function";
    }
    passedByReference(array);
    expect(array[1]).toBe(FILL_ME_IN);

    var assignedArray = array;
    assignedArray[5] = "changed in assignedArray";
    expect(array[5]).toBe(FILL_ME_IN);

    var copyOfArray = array.slice();
    copyOfArray[3] = "changed in copyOfArray";
    expect(array[3]).toBe(FILL_ME_IN);
  });

  it("should push and pop", function() {
    var array = [1, 2];
    array.push(3);

    expect(array).toEqual(FILL_ME_IN);

    var poppedValue = array.pop();
    expect(poppedValue).toBe(FILL_ME_IN);
    expect(array).toEqual(FILL_ME_IN);
  });

  it("should know about shifting arrays", function() {
    var array = [1, 2];

    array.unshift(3);
    expect(array).toEqual(FILL_ME_IN);

    var shiftedValue = array.shift();
    expect(shiftedValue).toEqual(FILL_ME_IN);
    expect(array).toEqual(FILL_ME_IN);
  });
});
<commit_msg>Filled in correct values in all .toBe() methods under "should create arrays" block<commit_after>describe("About Arrays", function() {

  // We shall contemplate truth by testing reality, via spec expectations.
  it("should create arrays", function() {
    var emptyArray = [];
    expect(typeof(emptyArray)).toBe('object'); // A mistake?-- http:javascript.crockford.com/remedial.html
    expect(emptyArray.length).toBe(0);

    var multiTypeArray = [0, 1, "two", function() { return 3; }, {value1: 4, value2: 5}, [6, 7]];
    expect(multiTypeArray[0]).toBe(0);
    expect(multiTypeArray[2]).toBe("two");
    expect(multiTypeArray[3]()).toBe(3);
    expect(multiTypeArray[4].value1).toBe(4);
    expect(multiTypeArray[4]["value2"]).toBe(5);
    expect(multiTypeArray[5][0]).toBe(6);
  });

  it("should understand array literals", function() {
    var array = [];
    expect(array).toEqual([]);

    array[0] = 1;
    expect(array).toEqual([1]);

    array[1] = 2;
    expect(array).toEqual([1, FILL_ME_IN]);

    array.push(3);
    expect(array).toEqual(FILL_ME_IN);
  });

  it("should understand array length", function() {
    var fourNumberArray = [1, 2, 3, 4];

    expect(fourNumberArray.length).toBe(FILL_ME_IN);
    fourNumberArray.push(5, 6);
    expect(fourNumberArray.length).toBe(FILL_ME_IN);

    var tenEmptyElementArray = new Array(10);
    expect(tenEmptyElementArray.length).toBe(FILL_ME_IN);

    tenEmptyElementArray.length = 5;
    expect(tenEmptyElementArray.length).toBe(FILL_ME_IN);
  });

  it("should slice arrays", function() {
    var array = ["peanut", "butter", "and", "jelly"];

    expect(array.slice(0, 1)).toEqual(FILL_ME_IN);
    expect(array.slice(0, 2)).toEqual(FILL_ME_IN);
    expect(array.slice(2, 2)).toEqual(FILL_ME_IN);
    expect(array.slice(2, 20)).toEqual(FILL_ME_IN);
    expect(array.slice(3, 0)).toEqual(FILL_ME_IN);
    expect(array.slice(3, 100)).toEqual(FILL_ME_IN);
    expect(array.slice(5, 1)).toEqual(FILL_ME_IN);
  });

  it("should know array references", function() {
    var array = [ "zero", "one", "two", "three", "four", "five" ];

    function passedByReference(refArray) {
      refArray[1] = "changed in function";
    }
    passedByReference(array);
    expect(array[1]).toBe(FILL_ME_IN);

    var assignedArray = array;
    assignedArray[5] = "changed in assignedArray";
    expect(array[5]).toBe(FILL_ME_IN);

    var copyOfArray = array.slice();
    copyOfArray[3] = "changed in copyOfArray";
    expect(array[3]).toBe(FILL_ME_IN);
  });

  it("should push and pop", function() {
    var array = [1, 2];
    array.push(3);

    expect(array).toEqual(FILL_ME_IN);

    var poppedValue = array.pop();
    expect(poppedValue).toBe(FILL_ME_IN);
    expect(array).toEqual(FILL_ME_IN);
  });

  it("should know about shifting arrays", function() {
    var array = [1, 2];

    array.unshift(3);
    expect(array).toEqual(FILL_ME_IN);

    var shiftedValue = array.shift();
    expect(shiftedValue).toEqual(FILL_ME_IN);
    expect(array).toEqual(FILL_ME_IN);
  });
});
<|endoftext|>


<commit_before>"use strict";

const Base = require("./Base");
const Collection = require("../util/Collection");
const VoiceState = require("./VoiceState");

/**
* Represents a call
* @prop {String} id The ID of the call
* @prop {Number} createdAt Timestamp of the call's creation
* @prop {GroupChannel} channel The call channel
* @prop {Collection<VoiceState>} voiceStates The voice states of the call participants
* @prop {String[]} participants The IDs of the call participants
* @prop {Number?} endedTimestamp The timestamp of the call end
* @prop {String[]?} ringing The IDs of people that still have not responded to the call request
* @prop {String?} region The region of the call server
* @prop {Boolean} unavailable Whether the call is unavailable or not
*/
class Call extends Base {
    constructor(data, channel) {
        super(data.id);
        this.channel = channel;
        this.voiceStates = new Collection(VoiceState);
        this.ringing = [];
        this.update(data);
    }

    update(data) {
        this.participants = data.participants !== undefined ? data.participants : this.participants || [];
        if(data.ringing !== undefined) {
            if(!~this.ringing.indexOf(this.channel.client.user.id) && ~(this.ringing = data.ringing).indexOf(this.channel.client.user.id)) {
                /**
                * Fired when the bot user is rung in a call
                * @event Client#callRing
                * @prop {Call} call The call
                */
                this.channel.client.emit("callRing", this);
            }
        }
        this.region = data.region !== undefined ? data.region : this.region || null;
        this.endedTimestamp = data.ended_timestamp !== undefined ? Date.parse(data.ended_timestamp) : this.endedTimestamp || null;
        this.unavailable = data.unavailable !== undefined ? data.unavailable : this.unavailable !== undefined ? this.unavailable : true;
        if(data.voice_states) {
            data.voice_states.forEach((voiceState) => {
                voiceState.id = voiceState.user_id;
                this.voiceStates.add(voiceState);
            });
        }
    }
}

module.exports = Call;<commit_msg>Fix internal Call channel references<commit_after>"use strict";

const Base = require("./Base");
const Collection = require("../util/Collection");
const VoiceState = require("./VoiceState");

/**
* Represents a call
* @prop {String} id The ID of the call
* @prop {Number} createdAt Timestamp of the call's creation
* @prop {GroupChannel} channel The call channel
* @prop {Collection<VoiceState>} voiceStates The voice states of the call participants
* @prop {String[]} participants The IDs of the call participants
* @prop {Number?} endedTimestamp The timestamp of the call end
* @prop {String[]?} ringing The IDs of people that still have not responded to the call request
* @prop {String?} region The region of the call server
* @prop {Boolean} unavailable Whether the call is unavailable or not
*/
class Call extends Base {
    constructor(data, channel) {
        super(data.id);
        this.channel = channel;
        this.voiceStates = new Collection(VoiceState);
        this.ringing = [];
        this.update(data);
    }

    update(data) {
        this.participants = data.participants !== undefined ? data.participants : this.participants || [];
        if(data.ringing !== undefined) {
            if(!~this.ringing.indexOf(this.channel._client.user.id) && ~(this.ringing = data.ringing).indexOf(this.channel._client.user.id)) {
                /**
                * Fired when the bot user is rung in a call
                * @event Client#callRing
                * @prop {Call} call The call
                */
                this.channel._client.emit("callRing", this);
            }
        }
        this.region = data.region !== undefined ? data.region : this.region || null;
        this.endedTimestamp = data.ended_timestamp !== undefined ? Date.parse(data.ended_timestamp) : this.endedTimestamp || null;
        this.unavailable = data.unavailable !== undefined ? data.unavailable : this.unavailable !== undefined ? this.unavailable : true;
        if(data.voice_states) {
            data.voice_states.forEach((voiceState) => {
                voiceState.id = voiceState.user_id;
                this.voiceStates.add(voiceState);
            });
        }
    }
}

module.exports = Call;<|endoftext|>