feat(parser): add split(), url, and diff() to Resource

This commit is contained in:
cswimr 2025-02-12 00:46:18 -06:00
parent 46f212423f
commit f302ec0d31
Signed by: cswimr
GPG key ID: 0EC431A8DA8F8087

View file

@ -33,6 +33,17 @@ export class Resource {
}
}
/**
* Creates a URL object from the Resource.
* @return A URL object representing the Resource. Will be a file URL if the path is not a valid URL.
*/
get url(): URL {
if (!this.isUrl) {
return new URL(`file://${this.path}`);
}
return new URL(this.path);
}
/**
* Gets the name of the file or URL.
* @return The name of the file or URL.
@ -94,6 +105,43 @@ export class Resource {
return fs.readFile(this.path, { encoding: "utf8" });
}
/**
* Splits the Resource path into an array of segments.
* @return An array of segments in the path, in order of occurrence.
*/
split(): string[] {
if (this.isUrl) {
return new URL(this.path).pathname
.split("/")
.filter((segment) => segment.length > 0);
}
return this.path.split(path.sep);
}
/**
* Compares the paths of two Resource instances and returns the differences.
* @param other - The other Resource instance to compare with.
* @return An array of segments that are different between the two paths.
*/
diff(other: Resource): string[] {
if (this.isUrl !== other.isUrl) {
throw new Error("Cannot diff URL and file paths");
}
const thisSegments = this.split();
const otherSegments = other.split();
const diff: string[] = [];
for (
let i = 0;
i < Math.max(thisSegments.length, otherSegments.length);
i++
) {
if (thisSegments[i] !== otherSegments[i]) {
diff.push(otherSegments[i]);
}
}
return diff;
}
/**
* Joins the Resource with other segments to create a new Resource.
* @param segments - The segments to join with the Resource.