1
0
mirror of https://github.com/janet-lang/janet synced 2024-12-23 15:00:27 +00:00

Add put-in.

This commit is contained in:
Calvin Rose 2019-09-05 13:19:25 -05:00
parent 7a13d24e6f
commit 99f147219a

View File

@ -961,14 +961,15 @@
(or d dflt))
(defn update-in
"Access a value in a nested data structure. Looks into the data structure via
"Update a value in a nested data structure by applying f to the current value.
Looks into the data structure via
a sequence of keys. Missing data structures will be replaced with tables. Returns
the modified, original data structure."
[ds ks f & args]
(var d ds)
(def len (length ks))
(if (< len 1) (error "expected at least 1 key in ks"))
(for i 0 (- len 1)
(def len-1 (- (length ks) 1))
(if (< len-1 0) (error "expected at least 1 key in ks"))
(for i 0 len-1
(def k (get ks i))
(def v (get d k))
(if (= nil v)
@ -976,11 +977,33 @@
(put d k newv)
(set d newv))
(set d v)))
(def last-key (last ks))
(def last-key (get ks len-1))
(def last-val (get d last-key))
(put d last-key (f last-val ;args))
ds)
(defn put-in
"Put a value into a nested data structure.
Looks into the data structure via
a sequence of keys. Missing data structures will be replaced with tables. Returns
the modified, original data structure."
[ds ks v]
(var d ds)
(def len-1 (- (length ks) 1))
(if (< len-1 0) (error "expected at least 1 key in ks"))
(for i 0 len-1
(def k (get ks i))
(def v (get d k))
(if (= nil v)
(let [newv (table)]
(put d k newv)
(set d newv))
(set d v)))
(def last-key (get ks len-1))
(def last-val (get d last-key))
(put d last-key v)
ds)
(defn update
"Accepts a key argument and passes its associated value to a function.
The key is the re-associated to the function's return value. Returns the updated