Skip to content

Instantly share code, notes, and snippets.

@wusher
Created August 19, 2020 16:30
Show Gist options
  • Save wusher/9c471adb5c8b23a5125e28b2bdfe31c4 to your computer and use it in GitHub Desktop.
Save wusher/9c471adb5c8b23a5125e28b2bdfe31c4 to your computer and use it in GitHub Desktop.
import { expect } from "chai";
function dig(obj: any, key: string): any {
return key.split(".").reduce((memo, keyPiece) => {
if (!Object.keys(memo).includes(keyPiece)) {
throw new Error("key not found");
}
return memo[keyPiece];
}, obj);
}
describe("dig", () => {
let obj: any;
beforeEach(() => {
obj = {
a: 1,
b: {
c: 2,
d: {
e: 3,
f: {
g: 4,
},
},
},
};
});
it("returns the result of a single key", () => {
expect(dig(obj, "a")).to.equal(obj.a);
});
it("returns the value of a nested key", () => {
expect(dig(obj, "b.d")).to.equal(obj.b.d);
});
it("returns the value of a very nested key", () => {
expect(dig(obj, "b.d.f.g")).to.equal(obj.b.d.f.g);
});
it('throws "key not found" if the key is empty', () => {
expect(() => {
dig(obj, "");
}).to.throw("key not found");
});
it('throws "key not found" if single key fails to match', () => {
expect(() => {
dig(obj, "z");
}).to.throw("key not found");
});
it('throws "key not found" if nests key fails to match', () => {
expect(() => {
dig(obj, "b.d.z");
}).to.throw("key not found");
});
});
dig
✓ returns the result of a single key
✓ returns the value of a nested key
✓ returns the value of a very nested key
✓ throws "key not found" if the key is empty
✓ throws "key not found" if single key fails to match
✓ throws "key not found" if nests key fails to match
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment