Add sets.keepItIf
This commit is contained in:
parent
7ab114e159
commit
a98ec09b0b
|
@ -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
|
||||||
|
|
|
@ -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,
|
||||||
|
|
|
@ -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
|
Loading…
Reference in New Issue