Created
February 24, 2018 03:38
-
-
Save evilsoft/b4bc8f23eae6e9f5b40860ea7d06773c to your computer and use it in GitHub Desktop.
This file contains hidden or 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
const State = require('crocks/State') | |
const { get } = State | |
const assign = require('crocks/helpers/assign') | |
const concat = require('crocks/pointfree/concat') | |
const constant = require('crocks/combinators/constant') | |
const flip = require('crocks/combinators/flip') | |
const isString = require('crocks/predicates/isString') | |
const liftA2 = require('crocks/helpers/liftA2') | |
const mapReduce = require('crocks/helpers/mapReduce') | |
const objOf = require('crocks/helpers/objOf') | |
const propPathOr = require('crocks/helpers/propPathOr') | |
const unless = require('crocks/logic/unless') | |
const combineState = | |
liftA2(assign) | |
const StateProp = s => ({ | |
s, | |
concat: ({ s: t }) => StateProp(combineState(s, t)), | |
fold: f => f(s), | |
evalWith: s.evalWith | |
}) | |
StateProp.Empty = | |
StateProp(get(constant({}))) | |
const composeState = (...readers) => | |
mapReduce(StateProp, flip(concat), StateProp.Empty, readers) | |
const getPropInner = | |
def => | |
(isValid = constant(true)) => | |
paths => | |
(name = paths[paths.length - 1]) => | |
get(propPathOr(def, paths)) | |
.map(unless(isValid, constant(def))) | |
.map(objOf(name)) | |
const getProp = | |
(name, path, def = 'Prop not found!', allowFalsey = true) => | |
getPropInner(def)(x => allowFalsey && !!x )(path)(name) | |
const getPropAsString = | |
getPropInner('')(isString) | |
const getInvoice = | |
getProp('invoice', [ 'Invoice', 'summary' ], 'default') | |
const getHeader = | |
getProp('header', [ 'context', 'header' ], 'Default Header') | |
const data = { | |
Invoice: { summary: 'summed up nice' }, | |
context: { | |
header: 'dat header' | |
} | |
} | |
composeState(getInvoice, getHeader) | |
.evalWith(data) | |
//=> { header: 'dat header', invoice: 'summed up nice' } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment