Last active
July 30, 2016 13:56
-
-
Save typeetfunc/2a3ea890b75158ac775265bc62af4a48 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// библиотечный код | |
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://goo.gl/nQB7ad - Ramda REPL