Skip to content

Commit

Permalink
fromValidator combinator for conversion from data.validator to lens
Browse files Browse the repository at this point in the history
  • Loading branch information
Eevert Saukkokoski committed Jul 17, 2014
1 parent cf84d49 commit 2116f09
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 2 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
"devDependencies": {
"chai": "^1.9.1",
"coffee-script": "^1.7.1",
"data.validation": "^1.2.0",
"grunt": "^0.4.5",
"grunt-coffeelint": "0.0.10",
"grunt-contrib-clean": "^0.5.0",
Expand Down
16 changes: 15 additions & 1 deletion src/agson/combinators.coffee
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{Just, Nothing, fromNullable} = require 'data.maybe'
{Just, Nothing, fromNullable, fromValidation} = require 'data.maybe'

lens = require('./Lens').of
{identity} = require './lenses'
Expand Down Expand Up @@ -58,7 +58,21 @@ product = do ->
abl.runM(result).modify -> mb
result

fromValidator = (validator) -> lens "validate", (ma) ->
get: ->
ma.chain (a) ->
fromValidation validator a

modify: (f) ->
ma.chain (a) ->
validb = fromValidation(validator a)
if validb.isJust
f validb
else
ma

module.exports = {
where
product
fromValidator
}
30 changes: 29 additions & 1 deletion test/agson/CombinatorSpec.coffee
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
{Just, Nothing} = require 'data.maybe'
Validation = require 'data.validation'

require('chai').should()

lenses = require '../../src/agson/lenses'
traversals = require '../../src/agson/traversals'
combinators = require '../../src/agson/combinators'
Expand Down Expand Up @@ -115,7 +118,7 @@ describe 'agson.combinators', ->

describe 'recursing down a cons list', ->
{recurse} = traversals

List =
Cons: (head, tail) -> {head, tail}
Nil: {}
Expand Down Expand Up @@ -182,3 +185,28 @@ describe 'agson.combinators', ->
.map((v) -> v + 1)
.should.deep.equal Just [2, { foo: 3 }, [ 4, { bar: 5 } ] ]

describe 'fromValidator', ->
{fromValidator} = combinators
{list} = traversals

numberValidator = (input) ->
if typeof input is 'number'
Validation.Success input
else
Validation.Failure ['not a number']

numberList = list.then(fromValidator numberValidator)

describe 'get', ->
it 'gets items through validator', ->
numberList
.run([1, 2, 3, 'foo'])
.get()
.should.deep.equal Just [ 1, 2, 3 ]

describe 'modify', ->
it 'modifies items through validator', ->
numberList
.run([1, 2, 3, 'foo'])
.map((v) -> v + 1)
.should.deep.equal Just [2, 3, 4, 'foo']

0 comments on commit 2116f09

Please sign in to comment.