add firstIndexOf, firstIndexWhere, firstWhere

This commit is contained in:
Emile Clark-Boman 2026-01-27 11:11:53 +10:00
parent 728cae7788
commit 2807535792
2 changed files with 18 additions and 4 deletions

View file

@ -63,7 +63,7 @@ in rec {
# S = toTypeSig type |> parseTypeSig |> map trimClassPrefix; # S = toTypeSig type |> parseTypeSig |> map trimClassPrefix;
# progress = l: x: let # progress = l: x: let
# index = firstIndexOf x l; # index = firstIndexOf x null l;
# in # in
# if index == null # if index == null
# then [] # then []

View file

@ -1,12 +1,16 @@
{...}: let {...}: let
inherit inherit
(builtins) (builtins)
all
elem
elemAt elemAt
foldl' foldl'
genList genList
length length
; ;
in rec { in rec {
contains = sub: list: all (x: elem x list) sub;
sublist = start: count: list: let sublist = start: count: list: let
len = length list; len = length list;
in in
@ -45,14 +49,14 @@ in rec {
fold' 0; fold' 0;
# REF: pkgs.lib.lists.findFirstIndex [MODIFIED] # REF: pkgs.lib.lists.findFirstIndex [MODIFIED]
firstIndexOf = x: list: let firstIndexWhere = pred: default: list: let
resultIndex = resultIndex =
foldl' ( foldl' (
index: el: index: el:
if index < 0 if index < 0
then then
# No match yet before the current index, we need to check the element # No match yet before the current index, we need to check the element
if el == x if pred el
then then
# We have a match! Turn it into the actual index to prevent future iterations from modifying it # We have a match! Turn it into the actual index to prevent future iterations from modifying it
-index - 1 -index - 1
@ -66,6 +70,16 @@ in rec {
list; list;
in in
if resultIndex < 0 if resultIndex < 0
then null then default
else resultIndex; else resultIndex;
firstIndexOf = x: firstIndexWhere (el: el == x);
# WARNING: returns `default` in the edgecase `pred el && el == null`
firstWhere = pred: default: list: let
index = firstIndexWhere pred null list;
in
if index == null
then default
else elemAt list index;
} }