UniRef: add MappedReferenceDetector implementation (#1509)

The current reference detection implementation internal to the GitHub plugin
uses a map similar to this. This class being near to that makes it easy to adopt.
It's also very simple to use for tests.
This commit is contained in:
Robin van Boven 2020-01-07 13:26:53 +01:00 committed by GitHub
parent 4bdc7a57b7
commit 821be0b46e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 72 additions and 0 deletions

View File

@ -1,3 +1,4 @@
//@flow
export type {URL, ReferenceDetector} from "./referenceDetector";
export {MappedReferenceDetector} from "./mappedReferenceDetector";

View File

@ -0,0 +1,26 @@
//@flow
import type {NodeAddressT} from "../graph";
import type {ReferenceDetector, URL} from "./referenceDetector";
/**
* A reference detector which uses a pregenerated `Map<URL, NodeAddressT>` as a
* lookup table.
*
* Note: this is sensitive to canonicalization issues because it's based on string
* comparisons. For example:
* - "http://foo.bar/123" != "http://foo.bar/123#chapter-2"
* - "http://foo.bar/?a=1&b=2" != "http://foo.bar/?b=2&a=1"
* - "http://foo.bar/space+bar" != "http://foo.bar/space%20bar"
*/
export class MappedReferenceDetector implements ReferenceDetector {
map: Map<URL, NodeAddressT>;
constructor(map: Map<URL, NodeAddressT>) {
this.map = map;
}
addressFromUrl(url: URL): ?NodeAddressT {
return this.map.get(url);
}
}

View File

@ -0,0 +1,45 @@
// @flow
import {type NodeAddressT, NodeAddress} from "../graph";
import type {URL, ReferenceDetector} from "./referenceDetector";
import {MappedReferenceDetector} from "./mappedReferenceDetector";
const nodeA = NodeAddress.fromParts(["test", "A"]);
const nodeB = NodeAddress.fromParts(["test", "B"]);
const nodeC = NodeAddress.fromParts(["test", "C"]);
describe("core/references/mappedReferenceDetector", () => {
describe("MappedReferenceDetector", () => {
it("should implement the ReferenceDetector interface", () => {
const _unused_toReferenceDetector = (
x: MappedReferenceDetector
): ReferenceDetector => x;
});
it("should return values of exactly matching keys in the map", () => {
// Given
const map: Map<URL, NodeAddressT> = new Map([
["http://foo.bar/a", nodeA],
["http://foo.bar/b", nodeB],
["http://foo.bar/c", nodeC],
]);
// When
const refs = new MappedReferenceDetector(map);
const n1a = refs.addressFromUrl("http://foo.bar/a");
const n2a = refs.addressFromUrl("http://foo.bar/b");
const n3a = refs.addressFromUrl("http://foo.bar/c");
const n1b = refs.addressFromUrl("https://foo.bar/a");
const n2b = refs.addressFromUrl("http://foo.bar/b?key=val");
const n3b = refs.addressFromUrl("http://foo.bar/c#anchor");
// Then
expect(n1a).toEqual(nodeA);
expect(n2a).toEqual(nodeB);
expect(n3a).toEqual(nodeC);
expect(n1b).toEqual(undefined);
expect(n2b).toEqual(undefined);
expect(n3b).toEqual(undefined);
});
});
});