myPatterns: XPath / RegEx for JS Objects
myPatterns is a new library adding custom notations for data structures in JS (and also C). It’s really useful for writing elegant programs using general pattern matching.
To explain myPatterns, let’s introduce a standard JavaScript object:
PLAIN TEXT
JavaScript
1 |
( |
2 | name: { firstname: "John", lastname: "Smith" }, |
3 | children: [ |
4 | { firstname: "Eric", gender: "male", born: 1991 }, |
5 | { firstname: "Deborah", gender: "female", born: 1996 } |
6 | ] |
7 | } |
Using myPattern, you can write a test to check if this object represents a person whose first child is a boy 18 years old:
JavaScript:
1 |
(s = match(x, "{name:{lastname: %l}, children:[{gender: ‘male’, born: %b} | %x]}")) |
2 | && new Date().getFullYear() – s.b == 18 |
The website explains the pattern above:
In the above, the match() statement both checks whether the object has a certain form (e.g. that the children field is an array containing a first element of a given form), and returns a "substitution" object s having the following value: {l: "Smith", b: 1991, x: [ {firstname: "Deborah" , born: 1996} ]}.
Furthermore, using your own notations, you could write the same condition more concisely, and with your own personal touch, for example:
PLAIN TEXT
JavaScript:
s = match(x, "<%first ~ %last: [boy(18) | %rest]>")
In the above, the object is noted in a more concise way, and the age of the first son is directly specified in the pattern, as if it was stored in the object, taking advantage of active patterns to compute the age on the fly.
Neat!