As programmers we rarely have a luxury to write a project from scratch. Usually we have
to retrofit existing projects with all cool things we need. If a new component, or a library
we want to use introduces new concepts that bleed outside its boundary, we have a “culture clash”,
when old code is unaware about new concepts have to work with it anyhow. Sometimes the clash is so bad
that we have to give up on using shiny new things, or have to significantly rework their code,
which requires time and efforts we cannot afford.
Incomplete objects allow us to concentrate on important properties of JavaScript objects
ignoring the rest: we don’t need to specify every single property, and we can deal with
cyclical graphs.
Incomplete arrays is a complimentary feature to inspect only the first few array items.
Both features are very useful for patterns, and heya-unify
provides rich facilities to automate
creating incomplete objects: they can be marked up explicitly on per-instance basis, recursively
with a special utility, and we can specify how to deal with objects by default during unification.
Custom unification in heya-unify
allows us to deal with our specific objects in JavaScript,
create unification helpers, and even custom logical conditions. It is there to bridge unification
with our existing projects.
Looking at the 1st part
and
the 2nd part
of the series is recommended before diving into details.
Custom unification
Unification makes comparing simple objects a cinch no matter how complex they are, and we can easily apply it
to JSON-like trees as is. Additionally heya-unify
“knows” how to unify other common JavaScript objects:
dates, and regular expressions. Yet in Real Life™ we are faced with complications like that:
Unification for JS
introduced heya-unify
—
a practical mini library to leverage unification in JavaScript. This post explains when
it makes sense to use unification, and gives practical examples of how to use it.
When to unify?
Below is my laundry list for unification. As soon as I see a project, which deals with items on
the list, I investigate if it makes sense to use heya-unify
.
Unification is a very interesting programming tool. Originated from logical programming
(its the foundation of Prolog) and used in functional programming (e.g., Haskell) it helps
to compare objects for equality, identify known patterns, and reassemble results differently.
Wikipedia gives a somewhat complex definition
of unification, but many people see it as
an extended equivalence comparison, a pattern matching tool, and some even find parallels with
XPath queries, CSS, and even jQuery, all operating on regular objects. See it for yourself.