Skip to content

Instantly share code, notes, and snippets.

@rjhilgefort
Created October 29, 2018 20:35
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 rjhilgefort/8b6dd66fc75a2f1b45812e7aecbc69b5 to your computer and use it in GitHub Desktop.
Save rjhilgefort/8b6dd66fc75a2f1b45812e7aecbc69b5 to your computer and use it in GitHub Desktop.
// `tryCatch` is useful when you want to do assignment and have a sane default
// The value provided is not parseable, so we get `{}` because there was an error
tryCatch(JSON.parse, always({}))('{{50')
// {}
// Here, the value is parseable, so we get the parsed object literal
tryCatch(JSON.parse, always({}))('{ "foo": "HI" }')
// {"foo": "HI"}
// ---------------------------------------
// Let's make a safe JSON.parse
const jsonParse = curry((defaultValue, x) =>
tryCatch(JSON.parse, always(defaultValue))(x)
)
const foo = jsonParse('nope', '54 {}')
// 'nope'
const bar = jsonParse('nope', '{}')
// {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment