Skip to content

Commit

Permalink
Merge pull request #43 from brightcove/union-list-map
Browse files Browse the repository at this point in the history
Allow Lists, Maps, and Records to coexist in a Union
  • Loading branch information
stutrek committed Feb 23, 2017
2 parents 44c2a0a + 0e5db20 commit c9a1cbf
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 3 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,5 @@ node_modules

# build artifacts
**/lib/*

.idea
23 changes: 23 additions & 0 deletions src/test/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import test from "./test"
import * as Immutable from "immutable"
import {List} from "../list"
import {Map} from "../map"
import {Record} from "../record"
import {Typed, typeOf, Union, Range, Maybe} from "../typed"

Expand Down Expand Up @@ -567,3 +569,24 @@ test("Union of similar records", assert => {
assert.equal(Action({action: remove}).action, remove, "recognizes Remove")
assert.ok(Action({action: ambigius}).action instanceof Add, "matches Add")
})

test("Union of lists, maps, and records", assert => {
const MyList = List(Number(0))
const MyMap = Map(String, String)
const MyRecord = Record({id: Number(0)})
const Action = Record({action: Union(MyList, MyMap, MyRecord)})

const myList = MyList()
const myMap = MyMap()
const myRecord = MyRecord()
const ambiguousList = [5]
const ambiguousMap = {id: 'foo'}
const ambiguousRecord = {id: 1}

assert.equal(Action({action: myList}).action, myList, "recognizes MyList")
assert.equal(Action({action: myMap}).action, myMap, "recognizes MyMap")
assert.equal(Action({action: myRecord}).action, myRecord, "recognizes MyRecord")
assert.ok(Action({action: ambiguousList}).action instanceof MyList, "matches MyList")
assert.ok(Action({action: ambiguousList}).action instanceof MyList, "matches MyMap")
assert.ok(Action({action: ambiguousRecord}).action instanceof MyRecord, "matches MyRecord")
})
13 changes: 10 additions & 3 deletions src/typed.js
Original file line number Diff line number Diff line change
Expand Up @@ -220,9 +220,16 @@ class UnionType extends Type {

index = 0
while (index < count) {
const result = variants[index][$read](value)
if (!(result instanceof TypeError)) {
return result
let result
try {
result = variants[index][$read](value)
if (!(result instanceof TypeError)) {
return result
}
} catch (ex) {
if (!(ex instanceof TypeError)) {
throw ex
}
}
index = index + 1
}
Expand Down

0 comments on commit c9a1cbf

Please sign in to comment.