Skip to content

Commit

Permalink
Adding in the compose2 combinator (evilsoft#431)
Browse files Browse the repository at this point in the history
* Adding in the `compose2` combinator

* Updates per review + minor doc fixes
  • Loading branch information
dalefrancis88 authored and evilsoft committed Jul 21, 2019
1 parent ce1fbd8 commit b2f8a77
Show file tree
Hide file tree
Showing 10 changed files with 228 additions and 24 deletions.
12 changes: 6 additions & 6 deletions docs/src/pages/docs/crocks/Async.md
Original file line number Diff line number Diff line change
Expand Up @@ -1397,10 +1397,10 @@ logResult(timeout(fast))
//=> resolved: "All good"

logResult(timeout(slow))
// => rejected: "Error: Request has timed out"
//=> rejected: "Error: Request has timed out"

logResult(failingPromise)
// => rejected: "Promise rejected!"
//=> rejected: "Promise rejected!"
```

#### eitherToAsync
Expand Down Expand Up @@ -1593,7 +1593,7 @@ Resolved(First.empty())
Resolved(First(42))
.chain(firstToAsync('Left'))
.fork(log('rej'), log('res'))
// => res: 42
//=> res: 42
```

#### lastToAsync
Expand Down Expand Up @@ -1694,7 +1694,7 @@ Resolved(Last.empty())
Resolved(Last('too know!'))
.chain(lastToAsync('Left'))
.fork(log('rej'), log('res'))
// => res: "too know!"
//=> res: "too know!"
```

#### maybeToAsync
Expand Down Expand Up @@ -1781,7 +1781,7 @@ Resolved(Nothing())
Resolved(Just('the 2 of us'))
.chain(maybeToAsync('Left'))
.fork(log('rej'), log('res'))
// => res: "the 2 of us"
//=> res: "the 2 of us"
```

#### resultToAsync
Expand Down Expand Up @@ -1868,7 +1868,7 @@ Resolved(Err('Invalid entry'))
Resolved(Ok('Success!'))
.chain(resultToAsync)
.fork(log('rej'), log('res'))
// => res: "Success!"
//=> res: "Success!"

```

Expand Down
4 changes: 2 additions & 2 deletions docs/src/pages/docs/crocks/Reader.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,11 @@ const flow =

flow
.runWith('Thomas')
// => Hola, Thomas...See Ya Thomas
//=> Hola, Thomas...See Ya Thomas

flow
.runWith('Jenny')
// => Hola, Jenny...See Ya Jenny
//=> Hola, Jenny...See Ya Jenny
```
<article id="topic-implements">

Expand Down
6 changes: 4 additions & 2 deletions docs/src/pages/docs/crocks/Tuple.md
Original file line number Diff line number Diff line change
Expand Up @@ -538,8 +538,10 @@ const Triple = Tuple(3)

const triple = Triple( 1, { key: 'value' }, 'string' )

tupleToArray(triple) // => [ 1, { key: 'value' }, 'string' ]
tupleToArray(triple)
//=> [ 1, { key: 'value' }, 'string' ]

tupleToArray(constant(triple))() // => [ 1, { key: 'value' }, 'string' ]
tupleToArray(constant(triple))()
//=> [ 1, { key: 'value' }, 'string' ]
```
</article>
128 changes: 125 additions & 3 deletions docs/src/pages/docs/functions/combinators.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,125 @@ give it a value and it will give you back a function ready to take a function.
Once that function is provided, it will return the result of applying your value
to that function.

#### compose2

`crocks/combinators/compose2`

```haskell
compose2 :: (c -> d -> e) -> (a -> c) -> (b -> d) -> a -> b -> e
```

`compose2` allows for composition between a `binary` function and
two `unary` functions. `compose2` takes a `binary` function followed by
two `unary` functions and returns a `binary` function that maps the first
argument with the first `unary` and the second with the second, passing
the results to the given `binary` and returning the result.

```javascript
import compose2 from 'crocks/combinators/compose2'

import and from 'crocks/logic/and'
import applyTo from 'crocks/combinators/applyTo'
import flip from 'crocks/combinators/flip'
import hasProp from 'crocks/predicates/hasProp'
import isNumber from 'crocks/predicates/isNumber'
import liftA2 from 'crocks/helpers/liftA2'
import map from 'crocks/pointfree/map'
import prop from 'crocks/Maybe/prop'
import safe from 'crocks/Maybe/safe'
import safeLift from 'crocks/Maybe/safeLift'

// isNonZero :: Number -> Boolean
const isNonZero = x =>
x !== 0

// isValidDivisor :: Number -> Boolean
const isValidDivisor =
and(isNumber, isNonZero)

// divideBy :: Number -> Number -> Number
const divideBy = x => y =>
y / x

// safeDivide :: Number -> Number -> Maybe Number
const safeDivide = compose2(
liftA2(divideBy),
safe(isValidDivisor),
safe(isNumber)
)

safeDivide(0.5, 21)
//=> Just 42

safeDivide('0.5', 21)
//=> Nothing

safeDivide(0.5, '21')
//=> Nothing

safeDivide(29, 0)
//=> Just 0

safeDivide(0, 29)
//=> Nothing

// Item :: { id: Integer }
// Items :: Array Item
const items =
[ { id: 2 }, { id: 1 } ]

// pluck :: String -> Array Object -> Maybe a
const pluck =
compose2(applyTo, prop, flip(map))

pluck('id', items)
//=> [ Just 2, Just 1 ]

// summarize :: String -> String -> String
const summarize = name => count =>
`${name} purchased ${count} items`

// getLength :: a -> Maybe Number
const getLength = safeLift(
hasProp('length'),
x => x.length
)

// createSummary :: Person -> Array Item -> String
const createSummary = compose2(
liftA2(summarize),
prop('name'),
getLength
)

createSummary({
name: 'Sam Smith'
}, items)
//=> Just "Sam Smith purchased 2 items"

// capitalize :: String -> String
const capitalize = str =>
`${str.charAt(0).toUpperCase()}${str.slice(1)}`

// join :: String -> String -> String -> String
const join = delim => right => left =>
`${left}${delim}${right}`

// toUpper :: String -> String
const toUpper = x =>
x.toUpperCase()

// createName :: String -> String -> String
const createName =
compose2(join(', '), capitalize, toUpper)

createName('Jon', 'doe')
//=> DOE, Jon

createName('sara', 'smith')
//=> SMITH, Sara
```

#### composeB

`crocks/combinators/composeB`
Expand Down Expand Up @@ -336,13 +455,16 @@ import liftA2 from 'crocks/helpers/liftA2'
import safe from 'crocks/Maybe/safe'

// isNonZero :: Number -> Boolean
const isNonZero = x => x !== 0
const isNonZero = x =>
x !== 0

// isValidDivisor :: Number -> Boolean
const isValidDivisor = and(isNumber, isNonZero)
const isValidDivisor =
and(isNumber, isNonZero)

// divideBy :: Number -> Number -> Number
const divideBy = x => y => y / x
const divideBy = x => y =>
y / x

// safeDivide :: Number -> Number -> Maybe Number
const safeDivide =
Expand Down
22 changes: 11 additions & 11 deletions docs/src/pages/docs/functions/helpers.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ const fluent = x =>
.chain(getProp('mi'))

fluent(data)
// => Just 'fa'
//=> Just 'fa'

// pointfree :: a -> Maybe b
const pointfree = compose(
Expand All @@ -104,7 +104,7 @@ const pointfree = compose(
)

pointfree(data)
// => Just 'fa'
//=> Just 'fa'
```

into the more abbreviated form:
Expand Down Expand Up @@ -133,7 +133,7 @@ const flow = composeK(
)

flow(data)
// => Just 'fa'
//=> Just 'fa'
```

As demonstrated in the above example, this function more closely resembles flows
Expand Down Expand Up @@ -265,7 +265,7 @@ const data =

composeS(double, avg)
.runWith(data)
// => 148
//=> 148
```

#### curry
Expand Down Expand Up @@ -651,7 +651,7 @@ const safeMax = mapReduce(
safeMax(data)
.option(Max.empty())
.valueOf()
// => 3
//=> 3
```

#### mconcat
Expand Down Expand Up @@ -798,7 +798,7 @@ const data =
[ 13, 5, 13 ]

map(max10, data)
// => [ 10, 5, 10]
//=> [ 10, 5, 10]
```

#### pick
Expand Down Expand Up @@ -874,15 +874,15 @@ const fluent = x =>
.chain(scaleLog(3))

fluent(0).log()
// => List [ "adding 4 to 0", "scaling 4 by 3" ]
//=> List [ "adding 4 to 0", "scaling 4 by 3" ]

const chainPipe = pipeK(
addLog(4),
scaleLog(3)
)

chainPipe(0).log()
// => List [ "adding 4 to 0", "scaling 4 by 3" ]
//=> List [ "adding 4 to 0", "scaling 4 by 3" ]
```

#### pipeP
Expand Down Expand Up @@ -1009,11 +1009,11 @@ const flow = (key, num) => pipeS(

flow('num', 10)
.runWith(data)
// => Just 66
//=> Just 66

flow('string', 100)
.runWith(data)
// => Nothing
//=> Nothing
```

#### setPath
Expand Down Expand Up @@ -1061,7 +1061,7 @@ setPath([ 'people', 2, 'age' ], 26, {
// ] }

setPath([ 'a', 'c' ], false, { a: { b: true } })
// => { a: { b: true, c: false } }
//=> { a: { b: true, c: false } }

setPath([ 'list', 'a' ], 'ohhh, I see.', { list: [ 'string', 'another' ] })
//=> { list: { 0: 'string', 1: 'another', a: 'ohhh, I see.' } }
Expand Down
16 changes: 16 additions & 0 deletions src/combinators/compose2.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/** @license ISC License (c) copyright 2019 original and current authors */
/** @author Dale Francis (dalefrancis88) */

const curry = require('../core/curry')
const isFunction = require('../core/isFunction')

// compose2 :: (c -> d -> e) -> (a -> c) -> (b -> d) -> a -> b -> e
function compose2(f, g, h, x, y) {
if(!isFunction(f) || !isFunction(g) || !isFunction(h)) {
throw new TypeError('compose2: First, second and third arguments must be functions')
}

return curry(f)(g(x), h(y))
}

module.exports = curry(compose2)
59 changes: 59 additions & 0 deletions src/combinators/compose2.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
const test = require('tape')
const helpers = require('../test/helpers')

const bindFunc = helpers.bindFunc

const isFunction = require('../core/isFunction')

const compose2 = require('./compose2')

test('compose2', t => {
const fn = bindFunc(compose2)
const f = x => y => x * y
const g = x => x - 1
const h = x => x + 1
const x = 22
const y = 1

t.ok(isFunction(compose2), 'is a function')

const err = /^TypeError: compose2: First, second and third arguments must be functions/
t.throws(fn(undefined, g, h, x, y), err, 'throws with first arg undefined')
t.throws(fn(null, g, h, x, y), err, 'throws with first arg null')
t.throws(fn(0, g, h, x, y), err, 'throws with first arg falsey number')
t.throws(fn(1, g, h, x, y), err, 'throws with first arg truthy number')
t.throws(fn('', g, h, x, y), err, 'throws with first arg falsey string')
t.throws(fn('string', g, h, x, y), err, 'throws with first arg truthy string')
t.throws(fn(false, g, h, x, y), err, 'throws with first arg false')
t.throws(fn(true, g, h, x, y), err, 'throws with first arg true')
t.throws(fn({}, g, h, x, y), err, 'throws with first arg an object')
t.throws(fn([], g, h, x, y), err, 'throws with first arg an array')

t.throws(fn(f, undefined, h, x, y), err, 'throws with second arg undefined')
t.throws(fn(f, null, h, x, y), err, 'throws with second arg null')
t.throws(fn(f, 0, h, x, y), err, 'throws with second arg falsey number')
t.throws(fn(f, 1, h, x, y), err, 'throws with second arg truthy number')
t.throws(fn(f, '', h, x, y), err, 'throws with second arg falsey string')
t.throws(fn(f, 'bling', h, x, y), err, 'throws with second arg truthy string')
t.throws(fn(f, false, h, x, y), err, 'throws with second arg false')
t.throws(fn(f, true, h, x, y), err, 'throws with second arg true')
t.throws(fn(f, {}, h, x, y), err, 'throws with second arg an object')
t.throws(fn(f, [], h, x, y), err, 'throws with second arg an array')

t.throws(fn(f, g, undefined, x, y), err, 'throws with third arg undefined')
t.throws(fn(f, g, null, x, y), err, 'throws with third arg null')
t.throws(fn(f, g, 0, x, y), err, 'throws with third arg falsey number')
t.throws(fn(f, g, 1, x, y), err, 'throws with third arg truthy number')
t.throws(fn(f, g, '', x, y), err, 'throws with third arg falsey string')
t.throws(fn(f, g, 'string', x, y), err, 'throws with third arg truthy string')
t.throws(fn(f, g, false, x, y), err, 'throws with third arg false')
t.throws(fn(f, g, true, x, y), err, 'throws with third arg true')
t.throws(fn(f, g, {}, x, y), err, 'throws with third arg an object')
t.throws(fn(f, g, [], x, y), err, 'throws with third arg an array')

const result = fn(f, g, h, x, y)

t.equal(result(), 42, 'returns expected result')

t.end()
})
Loading

0 comments on commit b2f8a77

Please sign in to comment.