Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Nested Object accessing without Maybe, maybe.
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
You can’t perform that action at this time.