Add tables.mgetOrPutLazy
This commit is contained in:
parent
4c695e5933
commit
40d0566ebf
|
@ -9,4 +9,15 @@ template init*[A, B](T: type OrderedTableRef[A, B]): auto = newOrderedTable[A, B
|
|||
template init*[A](T: type CountTable[A]): auto = initCountTable[A]()
|
||||
template init*[A](T: type CountTableRef[A]): auto = newCountTable[A]()
|
||||
|
||||
template mgetOrPutLazy*[A, B](t: Table[A, B], key: A, val: B): var B =
|
||||
type R = B
|
||||
|
||||
proc setter(loc: var R): var R =
|
||||
if loc == default(R):
|
||||
loc = val
|
||||
loc
|
||||
|
||||
setter(mgetOrPut(t, key, default(R)))
|
||||
|
||||
export tables, objects
|
||||
|
||||
|
|
|
@ -15,10 +15,11 @@ import
|
|||
test_bitops2,
|
||||
test_bitseqs,
|
||||
test_byteutils,
|
||||
test_ctops,
|
||||
test_endians2,
|
||||
test_macros,
|
||||
test_objects,
|
||||
test_ptrops,
|
||||
test_results,
|
||||
test_varints,
|
||||
test_ctops
|
||||
test_tables,
|
||||
test_varints
|
||||
|
|
|
@ -0,0 +1,15 @@
|
|||
import
|
||||
unittest,
|
||||
../stew/shims/tables
|
||||
|
||||
suite "tables":
|
||||
test "mgetOrPutLazy":
|
||||
var t = {"a": 10, "b": 20}.toTable
|
||||
check t.mgetOrPutLazy("a", 30) == 10
|
||||
check t.mgetOrPutLazy("c", 40) == 40
|
||||
|
||||
check t.mgetOrPutLazy("c", 20) == 40
|
||||
|
||||
t.mgetOrPutLazy("c", 20) = 15
|
||||
check t.mgetOrPutLazy("c", 40) == 15
|
||||
|
Loading…
Reference in New Issue