Skip to content

Commit 243a1c2

Browse files
committed
add array findlastindex
1 parent b5b75b2 commit 243a1c2

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

src/array-findlastindex.ts

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
export function arrayFindLastIndex<T>(
2+
this: T[],
3+
pred: (this: T[], value: T, i: number, array: T[]) => boolean,
4+
recv = this
5+
): number {
6+
for (let i = this.length; i > 0; i -= 1) {
7+
if (pred.call(recv, this[i], i, this)) return i
8+
}
9+
return -1
10+
}
11+
12+
/*#__PURE__*/
13+
export function isSupported(): boolean {
14+
return 'findLastIndex' in Array.prototype && typeof Array.prototype.findLastIndex === 'function'
15+
}
16+
17+
/*#__PURE__*/
18+
export function isPolyfilled(): boolean {
19+
return Array.prototype.findLastIndex === arrayFindLastIndex
20+
}
21+
22+
export function apply(): void {
23+
if (!isSupported()) {
24+
const defn = {
25+
value: arrayFindLastIndex,
26+
writable: true,
27+
configurable: true
28+
}
29+
Object.defineProperty(Array.prototype, 'findLastIndex', defn)
30+
}
31+
}

test/array-findlastindex.js

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import {apply, arrayFindLastIndex, isPolyfilled, isSupported} from '../lib/array-findlastindex.js'
2+
3+
describe('arrayFindLastIndex', () => {
4+
it('has standard isSupported, isPolyfilled, apply API', () => {
5+
expect(isSupported).to.be.a('function')
6+
expect(isPolyfilled).to.be.a('function')
7+
expect(apply).to.be.a('function')
8+
expect(isSupported()).to.be.a('boolean')
9+
expect(isPolyfilled()).to.equal(false)
10+
})
11+
12+
it('returns value that passes truthy', () => {
13+
expect(arrayFindLastIndex.call([1, 2, 3], v => v === 3)).to.equal(2)
14+
const arr = [1, 2, 3]
15+
const recv = {}
16+
expect(
17+
arrayFindLastIndex.call(
18+
arr,
19+
function (v, i, _arr) {
20+
// eslint-disable-next-line @typescript-eslint/no-invalid-this
21+
expect(this).to.equal(recv)
22+
expect(_arr).to.equal(arr)
23+
expect(v).to.equal(arr[i])
24+
},
25+
recv
26+
)
27+
)
28+
})
29+
})

0 commit comments

Comments
 (0)