Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jrgcubano/22dc96619d41234dfde8463c62976fba to your computer and use it in GitHub Desktop.
Save jrgcubano/22dc96619d41234dfde8463c62976fba to your computer and use it in GitHub Desktop.
Navigable Typescript object using arrows
class NavigableObject<T> {
constructor(private obj: T, private path: string[] = []) { }
To<R>(p: (x: T) => R): NavigableObject<R> {
return new NavigableObject<R>(p(this.obj),
this.path.concat(this.getPropName(p)));
}
getPath() {
return this.path;
}
private static propertyRegEx = /\.([^\.;]+);?\s*\}$/;
private getPropName(propertyFunction: Function) {
return NavigableObject.propertyRegEx.exec(propertyFunction.toString())[1];
}
}
let test = {
a: {
a1: 1,
a2: 1
},
b: {
b1: 1,
b2: 2
}
}
let navigableTest = new NavigableObject(test);
navigableTest.To(m => m.b).To(m => m.b2).getPath(); // = ["b", "b2"]
navigableTest.To(m => m.a).To(m => m.a2).getPath(); // = ["a", "a2"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment