Commit 260749e1 authored by Luke "Jared" Bennett's avatar Luke "Jared" Bennett

Add `.find` poly

parent fc035011
...@@ -6,3 +6,19 @@ Array.prototype.first = function() { ...@@ -6,3 +6,19 @@ Array.prototype.first = function() {
Array.prototype.last = function() { Array.prototype.last = function() {
return this[this.length-1]; return this[this.length-1];
} }
Array.prototype.find = Array.prototype.find || function(predicate, ...args) {
if (!this) throw new TypeError('Array.prototype.find called on null or undefined');
if (typeof predicate !== 'function') throw new TypeError('predicate must be a function');
const list = Object(this);
const thisArg = args[1];
let value = {};
for (let i = 0; i < list.length; i += 1) {
value = list[i];
if (predicate.call(thisArg, value, i, list)) return value;
}
return undefined;
};
...@@ -11,13 +11,36 @@ ...@@ -11,13 +11,36 @@
return expect(arr.first()).toBe(0); return expect(arr.first()).toBe(0);
}); });
}); });
return describe('last', function() { describe('last', function() {
return it('returns the last item', function() { return it('returns the last item', function() {
var arr; var arr;
arr = [0, 1, 2, 3, 4, 5]; arr = [0, 1, 2, 3, 4, 5];
return expect(arr.last()).toBe(5); return expect(arr.last()).toBe(5);
}); });
}); });
describe('find', function () {
beforeEach(() => {
this.arr = [0, 1, 2, 3, 4, 5];
});
it('returns the item that first passes the predicate function', () => {
expect(this.arr.find(item => item === 2)).toBe(2);
});
it('returns undefined if no items pass the predicate function', () => {
expect(this.arr.find(item => item === 6)).not.toBeDefined();
});
it('error when called on undefined or null', () => {
expect(Array.prototype.find.bind(undefined, item => item === 1)).toThrow();
expect(Array.prototype.find.bind(null, item => item === 1)).toThrow();
});
it('error when predicate is not a function', () => {
expect(Array.prototype.find.bind(this.arr, 1)).toThrow();
});
});
}); });
}).call(this); }).call(this);
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment