Add collection accessor methods: add/delete/get/has/set #74
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Following this comment on PR #68, this adds the following accessor functions to all collections:
add(value: any)
– adds a value to the collection. For!!map
and!!omap
thevalue
must be a Pair instance or a{ key, value }
object, which may not have a key that already exists in the map.delete(key: any): boolean
– removes a value from the collection. Returnstrue
if the item was found and removed.get(key: any, keepScalar: boolean?): any | undefined
– returns item atkey
, orundefined
if not found. IfkeepScalar
is not set, unwraps scalar values from their surrounding node; collections are always returned intact.has(key: any): boolean
– checks if the collection includes a value with the keykey
set(key: any, value: any)
– sets a value in this collection. For!!set
, value needs to be a boolean to add/remove the item from the set.For all of these, the keys may be nodes or their wrapped scalar values (i.e.
42
will matchScalar { value: 42 }
) . Keys for!!seq
should be positive integers, or their string representations.add()
andset()
do not automatically callcreateNode()
to wrap the value.Each of the methods also has a variant that requires an iterable as the first parameter, and allows fetching or modifying deeper collections:
addIn(path, value)
,deleteIn(path)
,getIn(path, keepScalar)
,hasIn(path)
,setIn(path, value)
.getIn
andhasIn
will returnundefined
orfalse
(respectively) if any of the intermediate collections is not found or if the key path attempts to extend within a scalar value, but the others will throw an error in such cases. Note that foraddIn
the path argument points to the collection rather than the item.The document also gets the same methods, based on the top-level collection (if any). For the
*in
methods using an emptypath
value (i.e.null
,undefined
, or[]
) will refer to the document's top-levelcontents
.Examples:
@MikeRalphson will this help with your usage with JSON pointers?
Edit 1: Added get/has/set to Document & dropped getIn/hasIn throwing for invalid key paths.
Edit 2: Added add/addIn/delete/deleteIn.