Add tables.mgetOrPutLazy

This commit is contained in:
Zahary Karadjov 2020-08-07 21:39:46 +03:00
parent 4c695e5933
commit 40d0566ebf
No known key found for this signature in database
GPG Key ID: C8936F8A3073D609
3 changed files with 29 additions and 2 deletions

View File

@ -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

View File

@ -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

15
tests/test_tables.nim Normal file
View File

@ -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