Returns a tree that can match against simple patterns or JavaScript regular expressions. This is useful in creating virtual trees.
For example, if you are creating a /user
area within a site that will handle routes like /user/[name].html
, you can use match()
to match that pattern and return a result.
$ ori match.ori
{
user = match('[name].html', =`<h1>${ _/name }</h1>`)
}
$ ori match.ori/user/Alice.html
<h1>Alice</h1>
The expression in parentheses defines a tree that matches patterns of the form [name].html
. This tree is then used to obtain a value for the key Alice.html
. Since that matches, the match()
generates a result — here, using a template.
The pattern
argument can take one of two forms:
- A simple pattern like
[name].html
. When used to matchAlice.html
, thefn
function will be given an object with the matches:{ name: "Alice" }
. - A standard JavaScript RegExp instance. In Origami you can create a regular expression with
RegExp
in thejs
namespace. If the regular expression matches, the groups that match will be passed to thefn
function.
By default, the tree will have no public keys, but you can provide any treelike object as the keys
argument. That tree’s values will be used as the keys for the tree returned by match()
.
$ ori matchDomain.ori
{
user = match('[name].html', =`<h1>${ _/name }</h1>`, [
"Alice.html"
"Bob.html"
"Carol.html"
])
}
$ ori matchDomain.ori
user:
Alice.html: <h1>Alice</h1>
Bob.html: <h1>Bob</h1>
Carol.html: <h1>Carol</h1>