Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# DevisPattern
<img src="https://avatars3.githubusercontent.com/u/21971184?v=4&amp;s=200" href="http://devisjs.surge.sh" width="250" />

>An exact-match pattern matcher on JavaScript object properties.
>A pattern matcher on JavaScript object properties.

<p align="center">
<a href="https://www.npmjs.com/package/devisPattern"><img src="https://img.shields.io/npm/v/devisPattern.svg" alt="Version"></a>
Expand Down Expand Up @@ -44,10 +44,21 @@ devisPattern.call({

## Matching rules

A pattern matches only an identical pattern: same keys, same values, same key order. Patterns are compared by their `JSON.stringify` form, so `{ a: 1, b: 2 }` and `{ b: 2, a: 1 }` are different patterns, and `{ a: 1 }` does not match `{ a: 1, b: 2 }`.
`find` matches only an identical pattern: same keys, same values, same key order. Patterns are compared by their `JSON.stringify` form, so `{ a: 1, b: 2 }` and `{ b: 2, a: 1 }` are different patterns, and `{ a: 1 }` does not match `{ a: 1, b: 2 }`.

When the same pattern is added twice, the first handler is kept.

`match` is the partial lookup used by Devis 4.1: a registered pattern matches when all its keys appear in the looked-up pattern with the same values. The pattern with the most keys wins, and the first registered wins a tie:

```JavaScript
devisPattern.add({ role: "math" }, any);
devisPattern.add({ role: "math", cmd: "sum" }, sum);

devisPattern.match({ role: "math", cmd: "sum", version: 2 }); // { handle: sum, size: 2 }
devisPattern.match({ role: "math", cmd: "divide" }); // { handle: any, size: 1 }
devisPattern.match({ cmd: "sum" }); // null
```

## API

### new DevisPattern()
Expand All @@ -62,6 +73,10 @@ Registers a pattern and the handler returned when an identical pattern is looked

Returns the handler registered for this pattern, or `null`.

### .match( {...pattern...} )

Returns `{ handle, size }` for the most specific registered pattern contained in this one, where `size` is its number of keys, or `null`.

### .call( {...pattern...}, [{...arguments...}], callback )

Calls the handler registered for this pattern with `(arguments, callback)`. `arguments` defaults to `{}`. Does nothing when no handler matches.
Expand Down
20 changes: 19 additions & 1 deletion devisPattern.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,17 @@ class devisPattern {
this.path = [];
this.id = 0;
this.index = new Map();
this.entries = [];
}

add(path, handle) {
this.path[this.id] = handle;
const key = JSON.stringify(path);
// First registration wins, as with the former native addon.
if (!this.index.has(key)) {this.index.set(key, this.id);}
if (!this.index.has(key)) {
this.index.set(key, this.id);
this.entries.push({ path: path, id: this.id });
}
this.id++;
return this;
}
Expand All @@ -24,6 +28,20 @@ class devisPattern {
else {return null;}
}

// Most specific registered pattern whose keys all appear in path with the same values; the first registered wins a tie.
match(path) {
const exact = this.find(path);
if (exact) {return { handle: exact, size: Object.keys(path).length };}
let best = null;
for (const entry of this.entries) {
const keys = Object.keys(entry.path);
if (best && keys.length <= best.size) {continue;}
const matches = keys.every((key) => Object.hasOwn(path, key) && JSON.stringify(path[key]) === JSON.stringify(entry.path[key]));
if (matches) {best = { handle: this.path[entry.id], size: keys.length };}
}
return best;
}

call(path, args, callback) {
if (!callback) {
callback = args;
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "devisPattern",
"version": "2.0.0",
"description": "An exact-match pattern matcher on JavaScript object properties",
"version": "2.1.0",
"description": "An exact and partial pattern matcher on JavaScript object properties",
"main": "devisPattern.js",
"files": [
"devisPattern.js"
Expand Down
44 changes: 44 additions & 0 deletions test/devisPattern.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,3 +67,47 @@ test("list returns a JSON array string of registered patterns", () => {
matcher.add({ cmd: "b", n: 1 }, () => {});
assert.deepStrictEqual(JSON.parse(matcher.list()), [{ cmd: "a" }, { cmd: "b", n: 1 }]);
});

test("match returns the handle of an identical pattern with its key count", () => {
const matcher = new DevisP();
const sum = () => {};
matcher.add({ role: "math", cmd: "sum" }, sum);
assert.deepStrictEqual(matcher.match({ role: "math", cmd: "sum" }), { handle: sum, size: 2 });
});

// A caller may send more keys than the handler cares about, such as a version or a tenant.
test("match resolves a registered pattern contained in a larger one", () => {
const matcher = new DevisP();
const sum = () => {};
matcher.add({ role: "math", cmd: "sum" }, sum);
assert.strictEqual(matcher.match({ role: "math", cmd: "sum", version: 2 }).handle, sum);
assert.strictEqual(matcher.match({ role: "math" }), null);
assert.strictEqual(matcher.match({ role: "math", cmd: "divide" }), null);
});

// A generic handler must not shadow a specific one, whatever the registration order.
test("match prefers the pattern with the most keys", () => {
const matcher = new DevisP();
const any = () => {};
const sum = () => {};
matcher.add({ role: "math" }, any);
matcher.add({ role: "math", cmd: "sum" }, sum);
assert.strictEqual(matcher.match({ role: "math", cmd: "sum", x: 1 }).handle, sum);
assert.strictEqual(matcher.match({ role: "math", cmd: "divide" }).handle, any);
});

test("match keeps the first registered pattern on a tie", () => {
const matcher = new DevisP();
const byRole = () => {};
matcher.add({ role: "math" }, byRole);
matcher.add({ cmd: "sum" }, () => {});
assert.strictEqual(matcher.match({ role: "math", cmd: "sum" }).handle, byRole);
});

test("match compares values, not only keys", () => {
const matcher = new DevisP();
matcher.add({ role: "math", options: { precise: true } }, () => {});
assert.notStrictEqual(matcher.match({ role: "math", options: { precise: true } }), null);
assert.strictEqual(matcher.match({ role: "math", options: { precise: false } }), null);
assert.strictEqual(matcher.match({ role: "1" }), null);
});
Loading