Skip to content

Instantly share code, notes, and snippets.

@ktheory
Last active May 19, 2017 14:01
Show Gist options
  • Save ktheory/e674c6426fe1bc4a24a73d8a11bc778d to your computer and use it in GitHub Desktop.
Save ktheory/e674c6426fe1bc4a24a73d8a11bc778d to your computer and use it in GitHub Desktop.
Implementing `gets` for Folktale.js

Motivation

I wanted to implement Sanctuary's gets function to safely access a nested path on an object, but using Folktale 1.0's functions.

This implementation relies on Folktale's core.operators.get function. Though it returns a Maybe instead of value | undefined.

The gets method is particular handy for AWS Lambda functions, where the passed event is often a deeply-nested object.

// Folktale dependencies
const O = require('core.operators');
const Maybe = require('data.maybe');
// gets([keys], object)
// [Strings] → Object → Just(α) | Nothing
//
// Takes an array of property names, and an object, and returns Just
// the value at the given path if such a path exists, Nothing otherwise.
//
// Similar to Sanctuary's `gets` without the predicate:
// https://sanctuary.js.org/#gets
const gets = (keys) => (data) =>
keys.reduce(
(acc, key) => acc.map(O.get(key)).chain(Maybe.fromNullable),
Maybe.of(data)
)
const data = { foo: { bar: {baz: 1}}}
console.log(gets(['foo', 'bar', 'baz'])(data))
// => Just(1)
console.log(gets(['foo', 'missingkey'])(data))
// => Nothing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment