All the code snippets on this page are live and interactive powered by the klipse plugin.
Zippers are a powerful abstraction for implementing arbitrary queries and transforms on immutable data structures and for step-by-step navigation and modification of data structures. This library implements a simple zipper designed for manipulating JSON data.
Playing with zippers in a REPL can be very instructive. First we require the libraries
import * as F from "fastener"
import * as R from "ramda"
and define a little helper using
reduce
to perform a sequence of
operations on a value:
var seq = (x, ...fs) => R.reduce((x, f) => f(x), x, fs)
Let's work with the following simple JSON object:
var data = {contents: [{language: "en", text: "Title"},
{language: "sv", text: "Rubrik"}]}
First we just create a zipper using F.toZipper
:
seq(F.toZipper(data))
As can be seen, the zipper is just a simple JSON object and the focus
is
the data
object that we gave to F.toZipper
. As long the data
structure being manipulated is JSON, you can serialize and deserialize zippers
as JSON. However, it is recommended that you use the zipper combinators to
operate on zippers rather than rely on their exact format.
Let's then move into the contents
property of the object using
F.downTo
:
seq(F.toZipper(data),
F.downTo('contents'))
As seen above, the focus
now has the contents
array. We can use
F.get
to extract the value under focus:
seq(F.toZipper(data),
F.downTo('contents'),
F.get)
Then we move into the first element of contents
using
F.downHead
:
seq(F.toZipper(data),
F.downTo('contents'),
F.downHead)
And continue into the first property of that which happens to be the language
:
seq(F.toZipper(data),
F.downTo('contents'),
F.downHead,
F.downHead)
And to the next property, title
, using F.right
:
seq(F.toZipper(data),
F.downTo('contents'),
F.downHead,
F.downHead,
F.right)
Let's then use F.modify
to modify the title
:
seq(F.toZipper(data),
F.downTo('contents'),
F.downHead,
F.downHead,
F.right,
F.modify(t => "The " + t))
When we now move outwards using F.up
we can see the changed title
become part of the data:
seq(F.toZipper(data),
F.downTo('contents'),
F.downHead,
F.downHead,
F.right,
F.modify(t => "The " + t),
F.up)
We can also just move back to the root and get the updated data structure using
F.fromZipper
:
seq(F.toZipper(data),
F.downTo('contents'),
F.downHead,
F.downHead,
F.right,
F.modify(t => "The " + t),
F.fromZipper)
The above hopefully helped to understand how zippers work. However, it is important to realize that one typically does not use zipper combinators to create such a specific sequence of operations. One rather uses the zipper combinators to create new combinators that perform more complex operations directly.
Let's first define a zipper combinator that, given a zipper focused on an array, tries to focus on an element inside the array that satisfies a given predicate:
var find = R.curry((p, z) => F.downTo(R.findIndex(p, F.get(z)), z))
Like all the basic zipper movement combinators, F.downTo
is a
partial function that returns undefined
in case the index is out of bounds.
Let's define a simple function to compose partial functions:
var pipePartial = (...fs) => z => {
for (let i=0; z !== undefined && i<fs.length; ++i)
z = fs[i](z)
return z
}
We can now compose a zipper combinator that, given a zipper focused on an object
like data
, tries to focus on the text
element of an object with the given
language
inside the contents
:
var textIn = language => pipePartial(
F.downTo('contents'),
find(R.whereEq({language})),
F.downTo('text'))
Now we can say:
seq(data,
F.toZipper,
textIn("en"),
F.modify(x => 'The ' + x),
F.fromZipper)
Of course, this just scratches the surface. Zippers are powerful enough to implement arbitrary transforms on data structures. This can also make them more difficult to compose and reason about than more limited approaches such as lenses.
The zipper combinators are available as named exports. Typically one just imports the library as:
import * as F from "fastener"
In the following examples we will make use of the function
var seq = (x, ...fs) => R.reduce((x, f) => f(x), x, fs)
written using reduce
that allows one
to express a sequence of operations to perform starting from a given value.
F.toZipper(json) ~> zipper
F.toZipper(json)
creates a new zipper that is focused on the root of the given
JSON object.
For example:
seq(F.toZipper([1,2,3]),
F.downHead,
F.modify(x => x + 1),
F.fromZipper)
F.fromZipper(zipper) ~> json
F.fromZipper(zipper)
extracts the modified JSON object from the given zipper.
For example:
seq(F.toZipper([1,2,3]),
F.downHead,
F.modify(x => x + 1),
F.fromZipper)
Focus combinators allow one to inspect and modify the element that a zipper is focused on.
F.get(zipper) ~> json
F.get(zipper)
returns the element that the zipper is focused on.
For example:
seq(F.toZipper(1), F.get)
seq(F.toZipper(["a","b","c"]),
F.downTo(2),
F.get)
F.modify(json => json, zipper) ~> zipper
F.modify(fn, zipper)
is equivalent to F.set(fn(F.get(zipper)), zipper)
and
replaces the element that the zipper is focused on with the value returned by
the given function for the element.
For example:
seq(F.toZipper(["a","b","c"]),
F.downTo(2),
F.modify(x => x + x),
F.fromZipper)
F.set(json, zipper) ~> zipper
F.set(json, zipper)
replaces the element that the zipper is focused on with
the given value.
For example:
seq(F.toZipper(["a","b","c"]),
F.downTo(1),
F.set('lol'),
F.fromZipper)
Movement combinators can be applied to any zipper, but they return undefined
in case of illegal moves.
Parent-Child movement is moving the focus between a parent object or array and a child element of said parent.
F.downHead(zipper) ~> maybeZipper
F.downHead(zipper)
moves the focus to the leftmost element of the object or
array that the zipper is focused on.
F.downLast(zipper) ~> maybeZipper
F.downLast(zipper)
moves the focus to the rightmost element of the object or
array that the zipper is focused on.
F.downTo(key, zipper) ~> maybeZipper
F.downTo(key, zipper)
moves the focus to the specified object property or
array index of the object or array that the zipper is focused on.
F.keyOf(zipper) ~> maybeKey
F.keyOf(zipper)
returns the object property name or the array index that the
zipper is currently focused on.
F.up(zipper) ~> maybeZipper
F.up(zipper)
moves the focus from an array element or object property to the
containing array or object.
Path movement is moving the focus along a path from a parent object or array to a nested child element.
F.downPath([...keys], zipper) ~> maybeZipper
F.downPath(path, zipper)
moves the focus along the specified path of keys.
F.pathOf(zipper) ~> [...keys]
F.pathOf(zipper)
returns the path from the root to the current element focused
on by the zipper.
Sibling movement is moving the focus between the elements of an array or an object.
F.head(zipper) ~> maybeZipper
F.head(zipper)
moves the focus to the leftmost sibling of the current focus.
F.last(zipper) ~> maybeZipper
F.last(zipper)
moves the focus to the rightmost sibling of the current focus.
F.left(zipper) ~> maybeZipper
F.left(zipper)
moves the focus to the element on the left of the current focus.
F.right(zipper) ~> maybeZipper
F.right(zipper)
moves the focus to the element on the right of the current focus.
F.queryMove(zipper => maybeZipper, value, zipper => value, zipper) ~> value
F.queryMove(move, default, fn, zipper)
applies the given function fn
to the
zipper focused on after the given movement and returns the result unless the
move was illegal in which case the given default value is returned instead.
For example:
seq(F.toZipper({x: 1}),
F.queryMove(F.downTo('y'), false, () => true))
seq(F.toZipper({y: 1}),
F.queryMove(F.downTo('y'), false, () => true))
F.transformMove(move, zipper => zipper, zipper) ~> zipper
F.transformMove(move, fn, zipper)
applies the given function to the zipper
focused on after the given movement. The movement move
must be one of
F.downHead
, F.downLast
,
F.downTo(key)
, F.left
, F.right
, or
F.up
. The function fn
must the return a zipper focused on the same
element that it was given. Then the focus is moved back to the element that the
zipper was originally focused on. Nothing is done in case of an illegal move.
For example:
seq(F.toZipper({y: 1}),
F.transformMove(F.downTo('y'), F.modify(x => x + 1)),
F.fromZipper)
seq(F.toZipper({x: 1}),
F.transformMove(F.downTo('y'), F.modify(x => x + 1)),
F.fromZipper)
F.everywhere(json => json, zipper) ~> zipper
F.everywhere(fn, zipper)
performs a transform of the focused element by
modifying each possible focus of the element with a bottom-up traversal.
For example:
seq(F.toZipper({foo: 1,
bar: [{lol: "bal", example: 2}]}),
F.everywhere(x => typeof x === "number" ? x + 1 : x),
F.fromZipper)
While the implementation is very different, the choice of combinators is based on Michael D. Adams' paper Scrap Your Zippers.
document.querySelector('.loading-message').className = "loading-hidden";
accelerate_klipse();