Skip to content

Instantly share code, notes, and snippets.

@ddanielbee
Created May 17, 2018 15:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ddanielbee/db358c2ba15646ae40fa100d9b733faa to your computer and use it in GitHub Desktop.
Save ddanielbee/db358c2ba15646ae40fa100d9b733faa to your computer and use it in GitHub Desktop.
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