Skip to content

Commit

Permalink
feat(collections): add findLastIndex (#1062)
Browse files Browse the repository at this point in the history
  • Loading branch information
getspooky authored and ry committed Jul 30, 2021
1 parent 2943276 commit 2ca77cf
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 0 deletions.
32 changes: 32 additions & 0 deletions collections/find_last_index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.

import { Predicate } from "./types.ts";

/**
* Returns the index of the last element in the given array matching the given predicate
*
* Example:
*
* ```ts
* import { findLastIndex } from "./find_last_index.ts";
*
* const numbers = [ 4, 2, 7 ]
* const lastIndexNumber = findLastIndex(numbers, it => it % 2 === 0)
*
* console.assert(lastIndexNumber === 1)
* ```
*/
export function findLastIndex<T>(
array: Array<T>,
predicate: Predicate<T>,
): number {
for (let i = array.length - 1; i >= 0; i -= 1) {
const element = array[i];

if (predicate(element)) {
return i;
}
}

return -1;
}
47 changes: 47 additions & 0 deletions collections/find_last_index_test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.

import { assertEquals } from "../testing/asserts.ts";
import { findLastIndex } from "./find_last_index.ts";

function findLastIndexTest<I>(
input: [Array<I>, (element: I) => boolean],
expected: number,
message?: string,
) {
const actual = findLastIndex(...input);
assertEquals(actual, expected, message);
}

Deno.test({
name: "[collections/findLastIndex] empty input",
fn() {
findLastIndexTest([[], (_) => true], -1);
},
});

Deno.test({
name: "[collections/findLastIndex] no matches",
fn() {
findLastIndexTest([[9, 11, 13], (it) => it % 2 === 0], -1);
findLastIndexTest([["foo", "bar"], (it) => it.startsWith("z")], -1);
},
});

Deno.test({
name: "[collections/findLastIndex] only match",
fn() {
findLastIndexTest([[9, 12, 13], (it) => it % 2 === 0], 1);
findLastIndexTest([["zap", "foo", "bar"], (it) => it.startsWith("z")], 0);
},
});

Deno.test({
name: "[collections/findLastIndex] multiple matches",
fn() {
findLastIndexTest([[0, 1, 2, 3, 4, 5, 6], (it) => it % 2 === 0], 6);
findLastIndexTest(
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], (it) => it % 2 === 0],
8,
);
},
});

0 comments on commit 2ca77cf

Please sign in to comment.