Skip to content

Commit 8263817

Browse files
committed
Add Ptr#eval
1 parent e03e4f0 commit 8263817

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

src/index.test.ts

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import Ptr, { InvalidPtrError } from "./index";
1+
import Ptr, { InvalidPtrError, EvalError } from "./index";
22

33
describe("Ptr", () => {
44
describe("parse", () => {
@@ -35,4 +35,24 @@ describe("Ptr", () => {
3535
}).toThrowError(new InvalidPtrError(" "));
3636
});
3737
});
38+
39+
describe("eval", () => {
40+
it("handles evaluating JSON pointers against any input", () => {
41+
expect(Ptr.parse("").eval(null)).toEqual(null);
42+
expect(Ptr.parse("").eval(true)).toEqual(true);
43+
expect(Ptr.parse("").eval(3.14)).toEqual(3.14);
44+
expect(Ptr.parse("").eval("foo")).toEqual("foo");
45+
expect(Ptr.parse("").eval([])).toEqual([]);
46+
expect(Ptr.parse("").eval({})).toEqual({});
47+
expect(Ptr.parse("/foo").eval({ foo: "bar" })).toEqual("bar");
48+
expect(Ptr.parse("/0").eval(["bar"])).toEqual("bar");
49+
expect(Ptr.parse("/foo/1/bar").eval({foo: [null, { bar: "x" }]})).toEqual("x");
50+
});
51+
52+
it("returns an error when an instance lacks a property", () => {
53+
expect(() => { Ptr.parse("/foo").eval(3.14) }).toThrow(new EvalError(3.14, "foo"));
54+
expect(() => { Ptr.parse("/0").eval([]) }).toThrow(new EvalError([], "0"));
55+
expect(() => { Ptr.parse("/foo").eval({}) }).toThrow(new EvalError({}, "foo"));
56+
});
57+
});
3858
});

src/index.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,18 @@ export default class Ptr {
3737

3838
return `/${tokens.join("/")}`;
3939
}
40+
41+
public eval(instance: any): any {
42+
for (const token of this.tokens) {
43+
if (instance.hasOwnProperty(token)) {
44+
instance = instance[token];
45+
} else {
46+
throw new EvalError(instance, token);
47+
}
48+
}
49+
50+
return instance;
51+
}
4052
}
4153

4254
export class InvalidPtrError extends Error {
@@ -47,3 +59,14 @@ export class InvalidPtrError extends Error {
4759
this.ptr = ptr;
4860
}
4961
}
62+
63+
export class EvalError extends Error {
64+
public instance: any;
65+
public token: string;
66+
67+
constructor(instance: any, token: string) {
68+
super(`Error evaluating JSON Pointer: no attribute ${token} on ${instance}`);
69+
this.instance = instance;
70+
this.token = token;
71+
}
72+
}

0 commit comments

Comments
 (0)