Skip to content

Commit

Permalink
feat(defmulti): add .dependencies(), add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Nov 2, 2020
1 parent a339ee0 commit d15a159
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
10 changes: 10 additions & 0 deletions packages/defmulti/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import type {
Fn8,
FnAny,
IObjectOf,
Pair,
} from "@thi.ng/api";

export type DispatchFn = FnAny<PropertyKey>;
Expand Down Expand Up @@ -230,6 +231,15 @@ export interface MultiFnBase<I> {
* @param id - implementation ID
*/
ancestors(id: PropertyKey): Set<PropertyKey>;
/**
* Returns iterator of all known dispatch values and their dependencies in
* the hierarchy of dispatch values. Each dependency is encoded as `[value,
* parent-value?]`. If `parent-value` is undefined, the dispatch value has
* no parent.
*/
dependencies(): IterableIterator<
Pair<PropertyKey, PropertyKey | undefined>
>;
}

export interface MultiFn<T>
Expand Down
8 changes: 8 additions & 0 deletions packages/defmulti/src/defmulti.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,14 @@ export function defmulti<T>(f: any, ancestors?: AncestorDefs) {
fn.parents = (id: PropertyKey) => rels[<any>id];
fn.ancestors = (id: PropertyKey) =>
new Set<PropertyKey>(findAncestors([], rels, id));
fn.dependencies = function* () {
for (let a in rels) {
for (let b of rels[a]) yield [a, b];
}
for (let id in impls) {
!rels[id] && (yield [id, undefined]);
}
};
return fn;
}

Expand Down
21 changes: 21 additions & 0 deletions packages/defmulti/test/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,4 +129,25 @@ describe("defmulti", () => {
assert.strictEqual(foo({ id: "a", val: "alice" }), "foo: alice");
assert.strictEqual(bar({ id: "a", val: "alice" }), "bar: ALICE");
});

it("dependencies", () => {
const a = defmulti((x) => x);
assert.deepStrictEqual([...a.dependencies()], []);
a.add("a", () => { });
assert.deepStrictEqual([...a.dependencies()], [["a",undefined]]);
a.add("d",()=>{});
a.isa("b", "a");
a.isa("c", "b");
a.isa("e", "b");
assert.deepStrictEqual(
new Set([...a.dependencies()]),
new Set([
["b", "a"],
["c", "b"],
["e", "b"],
["a", undefined],
["d", undefined]
])
);
});
});

0 comments on commit d15a159

Please sign in to comment.