Tutorial: Support for Immutable

Support for Immutable

In an asynchronous code execution environment, use of immutable data containers — such as those provided by the immutable package — can simplify planning and reasoning about the code's behavior. Lenses and efficiently immutable data structures work together synergistically, yet not every application of lenses needs or wants the immutable package installed. To avoid introducing a dependency between this library and the immutable package, natural-lenses limits its importing from immutable to one dangling submodule. natural-lenses/immutable exports two objects, of which the lensFactory is the more convenient: it is a Factory customized with a container factory building immutable.Lists and immutable.Maps. That container factory is the other export, under the name containerFactory, which can be used in constructing a Factory.

The natural-lenses/immutable submodule also has a side-effect of polyfilling support for lenses into immutable types. Though immutable.List, immutable.Map, and immutable.OrderedMap classes share many interface semantics with ES6 container types, they are not identical and two specific behaviors have to be defined for the container types to work with lenses (both named by Symbols): lens.at_maybe and lens.clone. The first implements the behavior for returning a Maybe monad value for the given key/index, and the second implements cloning with potential modifications of set or spliceOut. Because the methods are named with Symbols defined by this package, this polyfill should not interfere with application code or any other libraries in use.

Importing natural-lenses/immutable also has the side-effect of polyfilling Optic with a getSeq method that constructs a Seq (from the immutable package) from the non-string iterable in the Optic's target slot (or from an empty array if the slot's contents are a string or not iterable).

Even if no modified clones are to be created, the lens.at_maybe must be defined for immutable container types to participate in lens getting, so it may be beneficial to run lens.polyfillImmutable on all immutable types that might be present in data to be queried with lenses.

Because this library does not declare a dependency on immutable, it is the responsibility of the including project to declare it's own dependency on both that package and this one if both are to be used.