Created
May 17, 2018 15:05
-
-
Save ddanielbee/db358c2ba15646ae40fa100d9b733faa to your computer and use it in GitHub Desktop.
Nested Object accessing without Maybe, maybe.
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
const NOTHING = {}; | |
const safeProperty = (obj, propertyName) => (obj[propertyName] ? obj[propertyName] : NOTHING); | |
const recurProperties = (obj, ...propertyNames) => | |
propertyNames.reduce( | |
(accValue, currentProperty) => | |
accValue[currentProperty] ? accValue[currentProperty] : NOTHING, | |
obj | |
); | |
const ifPropertyThen = (fn, obj, ...propertyNames) => | |
recurProperties(obj, ...propertyNames) === NOTHING ? NOTHING : fn(obj); | |
describe("The safeProperty function", () => { | |
it("should return NOTHING if the property doesn't exist", () => { | |
const expected = NOTHING; | |
const actual = safeProperty({}, "prop"); | |
expect(expected).toBe(actual); | |
}); | |
it("should return the property if it exists", () => { | |
const expected = "property"; | |
const actual = safeProperty({ prop: "property" }, "prop"); | |
expect(expected).toBe(actual); | |
}); | |
}); | |
describe("The recurProperties function", () => { | |
it("should return NOTHING if the first property doesn't exist", () => { | |
const expected = NOTHING; | |
const actual = recurProperties({}, "prop"); | |
expect(expected).toBe(actual); | |
}); | |
it("should return NOTHING if the second property doesn't exist", () => { | |
const expected = NOTHING; | |
const actual = recurProperties({ prop: "notAnObject" }, "prop", "secondProp"); | |
expect(expected).toBe(actual); | |
}); | |
it("should return return the second property if it exists", () => { | |
const expected = "hello"; | |
const actual = recurProperties({ prop: { secondProp: "hello" } }, "prop", "secondProp"); | |
expect(expected).toBe(actual); | |
}); | |
}); | |
describe("The ifPropertyThen function", () => { | |
it("should return Nothing if the property doesn't exist", () => { | |
const expected = NOTHING; | |
const actual = ifPropertyThen(x => x, {}, "prop"); | |
expect(expected).toBe(actual); | |
}); | |
it("should apply the function given to the object passed and return its result", () => { | |
const expected = { prop: 2 }; | |
const actual = ifPropertyThen( | |
x => { | |
x.prop++; | |
return x; | |
}, | |
{ prop: 1 }, | |
"prop" | |
); | |
expect(expected).toEqual(actual); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment