Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(pathref): add custom instanceof which will work between versions #103

Merged
merged 1 commit into from
Feb 12, 2023
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
18 changes: 17 additions & 1 deletion src/path.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { assert, assertEquals, assertRejects, assertThrows, withTempDir } from "./deps.test.ts";
import { createPathRef } from "./path.ts";
import { createPathRef, PathRef } from "./path.ts";
import { path as stdPath } from "./deps.ts";

Deno.test("join", () => {
Expand Down Expand Up @@ -489,3 +489,19 @@ Deno.test("pipeTo", async () => {
assertEquals(otherFilePath.textSync(), largeText);
});
});

Deno.test("instanceof check", () => {
class OtherPathRef {
// should match because of this
private static instanceofSymbol = Symbol.for("dax.PathRef");

static [Symbol.hasInstance](instance: any) {
return instance?.constructor?.instanceofSymbol === OtherPathRef.instanceofSymbol;
}
}

assert(createPathRef("test") instanceof PathRef);
assert(!(new URL("https://example.com") instanceof PathRef));
assert(new OtherPathRef() instanceof PathRef);
assert(createPathRef("test") instanceof OtherPathRef);
});
12 changes: 12 additions & 0 deletions src/path.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,22 @@ export function createPathRef(path: string | URL): PathRef {
export class PathRef {
readonly #path: string;

/** This is a special symbol that allows different versions of
* Dax's `PathRef` API to match on `instanceof` checks. Ideally
* people shouldn't be mixing versions, but if it happens then
* this will maybe reduce some bugs (or cause some... tbd).
*/
private static instanceofSymbol = Symbol.for("dax.PathRef");

constructor(path: string | URL) {
this.#path = path instanceof URL ? stdPath.fromFileUrl(path) : path;
}

static [Symbol.hasInstance](instance: any) {
// this should never change because it should work accross versions
return instance?.constructor?.instanceofSymbol === PathRef.instanceofSymbol;
}

/** Gets the string representation of this path. */
toString(): string {
return this.#path;
Expand Down