2024-01-01 21:11:32 +00:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
2021-09-18 18:29:29 +00:00
|
|
|
// This module is browser compatible.
|
|
|
|
|
2021-09-01 06:51:02 +00:00
|
|
|
/**
|
|
|
|
* Returns all elements in the given array after the last element that does not
|
|
|
|
* match the given predicate.
|
|
|
|
*
|
2024-05-20 07:34:47 +00:00
|
|
|
* @typeParam T The type of the array elements.
|
2024-05-06 07:51:20 +00:00
|
|
|
*
|
|
|
|
* @param array The array to take elements from.
|
|
|
|
* @param predicate The predicate function to determine if an element should be
|
|
|
|
* included.
|
|
|
|
*
|
|
|
|
* @returns A new array containing all elements after the last element that does
|
|
|
|
* not match the predicate.
|
|
|
|
*
|
|
|
|
* @example Basic usage
|
2021-09-01 06:51:02 +00:00
|
|
|
* ```ts
|
2024-04-29 02:57:30 +00:00
|
|
|
* import { takeLastWhile } from "@std/collections/take-last-while";
|
refactor(assert,async,bytes,cli,collections,crypto,csv,data-structures,datetime,dotenv,encoding,expect,fmt,front-matter,fs,html,http,ini,internal,io,json,jsonc,log,media-types,msgpack,net,path,semver,streams,testing,text,toml,ulid,url,uuid,webgpu,yaml): import from `@std/assert` (#5199)
* refactor: import from `@std/assert`
* update
2024-06-30 08:30:10 +00:00
|
|
|
* import { assertEquals } from "@std/assert";
|
2021-09-01 06:51:02 +00:00
|
|
|
*
|
2024-05-06 07:51:20 +00:00
|
|
|
* const numbers = [1, 2, 3, 4, 5, 6];
|
|
|
|
*
|
|
|
|
* const result = takeLastWhile(numbers, (number) => number > 4);
|
2021-09-01 06:51:02 +00:00
|
|
|
*
|
2024-05-06 07:51:20 +00:00
|
|
|
* assertEquals(result, [5, 6]);
|
2021-09-01 06:51:02 +00:00
|
|
|
* ```
|
|
|
|
*/
|
|
|
|
export function takeLastWhile<T>(
|
|
|
|
array: readonly T[],
|
|
|
|
predicate: (el: T) => boolean,
|
|
|
|
): T[] {
|
|
|
|
let offset = array.length;
|
2024-02-02 06:01:54 +00:00
|
|
|
while (0 < offset && predicate(array[offset - 1] as T)) offset--;
|
2021-09-01 06:51:02 +00:00
|
|
|
|
|
|
|
return array.slice(offset, array.length);
|
|
|
|
}
|