Add .find poly

This commit is contained in:
Luke "Jared" Bennett 2016-11-23 15:54:35 +00:00
parent fc03501183
commit 260749e164
No known key found for this signature in database
GPG key ID: 402ED51FB5D306C2
4 changed files with 70 additions and 31 deletions

View file

@ -1,8 +0,0 @@
/* eslint-disable no-extend-native, func-names, space-before-function-paren, semi, space-infix-ops, max-len */
Array.prototype.first = function() {
return this[0];
}
Array.prototype.last = function() {
return this[this.length-1];
}

View file

@ -0,0 +1,24 @@
/* eslint-disable no-extend-native, func-names, space-before-function-paren, semi, space-infix-ops, max-len */
Array.prototype.first = function() {
return this[0];
}
Array.prototype.last = function() {
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;
};

View file

@ -1,23 +0,0 @@
/* eslint-disable space-before-function-paren, no-var, padded-blocks */
/*= require extensions/array */
(function() {
describe('Array extensions', function() {
describe('first', function() {
return it('returns the first item', function() {
var arr;
arr = [0, 1, 2, 3, 4, 5];
return expect(arr.first()).toBe(0);
});
});
return describe('last', function() {
return it('returns the last item', function() {
var arr;
arr = [0, 1, 2, 3, 4, 5];
return expect(arr.last()).toBe(5);
});
});
});
}).call(this);

View file

@ -0,0 +1,46 @@
/* eslint-disable space-before-function-paren, no-var, padded-blocks */
/*= require extensions/array */
(function() {
describe('Array extensions', function() {
describe('first', function() {
return it('returns the first item', function() {
var arr;
arr = [0, 1, 2, 3, 4, 5];
return expect(arr.first()).toBe(0);
});
});
describe('last', function() {
return it('returns the last item', function() {
var arr;
arr = [0, 1, 2, 3, 4, 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);