Created
August 19, 2020 16:30
-
-
Save wusher/9c471adb5c8b23a5125e28b2bdfe31c4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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