Skip to content

Instantly share code, notes, and snippets.

@fetchTe
Last active April 9, 2016 19:11
Show Gist options
  • Save fetchTe/4adb079615d159540b7bb020391cad26 to your computer and use it in GitHub Desktop.
Save fetchTe/4adb079615d159540b7bb020391cad26 to your computer and use it in GitHub Desktop.
Ramda and Sanctuary Learning
var safeHead = function(xs) {
  return S.ifElse(() => R.isNil(xs[0]), S.Nothing, S.Just, xs[0]);
};

const streetName = S.pipe([R.prop('addresses'), safeHead, R.map(R.prop('street'))]);

streetName({
  addresses: []
});
//Maybe {isNothing: true, isJust: false}

streetName({
  addresses: [{
    street: 'Shady Ln.',
    number: 4201
  }]
});
// Maybe {isNothing: false, isJust: true, value: "Shady Ln."}
// safeProp :: Key -> {Key: a} -> Maybe a
const safeProp = R.curry(function (type, key, obj) {
  return S.get(type, key, obj);
});

// chain :: Monad m => (a -> m b) -> m a -> m b
const chain = R.curry(function (f, m) {
  return m.chain(f);
});

// firstAddressStreet :: User -> Maybe City
const firstAddressStreet = S.pipe([
  safeProp(Array, 'addresses'),
  chain(S.head),
  chain(safeProp(String, 'city'))
]);

firstAddressStreet({
  addresses: [{
    street: {
      name: 'Not Quite Sure',
      number: 1102
    },
    city: 'Minneapolis',
    postcode: 55401
  }]
});
// Maybe {isNothing: false, isJust: true, value: "Minneapolis"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment