Skip to content

Instantly share code, notes, and snippets.

@typeetfunc
Last active July 30, 2016 13:56
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 typeetfunc/2a3ea890b75158ac775265bc62af4a48 to your computer and use it in GitHub Desktop.
Save typeetfunc/2a3ea890b75158ac775265bc62af4a48 to your computer and use it in GitHub Desktop.
// библиотечный код
var // определение Option и функции которая оброрачивает в нее
Some = val => [val],
None = [],
Of = val => isNil(val) ? None : Some(val),
applyOption = fn => curryN(fn.length, compose(Of, fn)),
isNone = option => option.length === 0,
flatMap = chain,
getOrElse = defaultVal => option => isNone(option) ?
defaultVal :
option[0],
// вспомогательная функция которая возврашает свойство если оно функция
method = compose(
val => is(Function, val) ? val : undefined,
prop
),
// оборачиваем все функции в опшион интерфейс - теперь они вместо андефайнед будут возврашать None
findOrNone = applyOption(find),
propOrNone = applyOption(prop),
methodOrNone = applyOption(method),
callOrNone = applyOption(call);
// данные
var list = [
{
id: 1,
dataList: [
{
type: 'main',
getData: () => 123,
},
{
type: 'other',
data: 456
}
]
},
{
id: 2
}
]
// наша логика
var getDataById = (id, list) => pipe(
flatMap(findOrNone(propEq('id', id))),
flatMap(propOrNone('dataList')),
flatMap(findOrNone(propEq('type', 'main'))),
flatMap(methodOrNone('getData')),
flatMap(callOrNone),
getOrElse('NOT DATA')
)(Of(list))
getDataById(1, list)
@typeetfunc
Copy link
Author

typeetfunc commented Jul 30, 2016

http://goo.gl/nQB7ad - Ramda REPL

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment