Add sets.keepItIf

This commit is contained in:
Zahary Karadjov 2021-12-02 18:31:59 +02:00
parent 7ab114e159
commit a98ec09b0b
No known key found for this signature in database
GPG Key ID: C8936F8A3073D609
3 changed files with 47 additions and 2 deletions

View File

@ -1,4 +1,4 @@
import std/sets, ../objects import std/sets, ../objects, ../templateutils
when not declared(initHashSet): when not declared(initHashSet):
template initHashSet*[T](initialSize = 64): auto = template initHashSet*[T](initialSize = 64): auto =
@ -18,5 +18,16 @@ template init*[T](_: type set[T]): auto =
var x: set[T] var x: set[T]
x x
export sets, objects template keepItIf*[T](setParam: var HashSet[T], itPredicate: untyped) =
bind evalTemplateParamOnce
evalTemplateParamOnce(setParam, s):
var itemsToDelete: seq[T]
for it {.inject.} in s:
if not itPredicate:
itemsToDelete.add(it)
for item in itemsToDelete:
s.excl item
export sets, objects

View File

@ -27,6 +27,7 @@ import
test_ptrops, test_ptrops,
test_sequtils2, test_sequtils2,
test_sorted_set, test_sorted_set,
test_sets,
test_templateutils, test_templateutils,
test_results, test_results,
test_varints, test_varints,

33
tests/test_sets.nim Normal file
View File

@ -0,0 +1,33 @@
import
unittest,
../stew/shims/sets
suite "shims/sets":
test "keepItIf":
var s1 = init HashSet[int]
s1.incl 10
s1.incl 20
s1.incl 30
s1.keepItIf(it > 15)
check:
s1.len == 2
10 notin s1
20 in s1
30 in s1
var s2 = init HashSet[string]
s2.keepItIf(it.len > 0)
check s2.len == 0
s2.incl "test"
s2.keepItIf(it.len > 10)
check s2.len == 0
s2.incl "test"
s2.keepItIf(it.len > 0)
check:
s2.len == 1
"test" in s2