Skip to content

Commit

Permalink
Introduce fromClass isomorphism to deal with non-Objects
Browse files Browse the repository at this point in the history
This partially addresses issue #40.
  • Loading branch information
polytypic committed Jan 10, 2017
1 parent 1ed8855 commit b497394
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/partial.lenses.js
Original file line number Diff line number Diff line change
Expand Up @@ -653,6 +653,17 @@ export const iso =

// Isomorphisms and combinators

export const fromClass = Class => {
const toClass = x => isObject(x)
? Object.assign(Object.create(Class.prototype), x)
: void 0
return (F, xi2yF, x, i) =>
(0,F.map)(toClass,
xi2yF(Object.getPrototypeOf(x).constructor === Class
? Object.assign({}, x)
: void 0, i))
}

export const identity = (_F, xi2yF, x, i) => xi2yF(x, i)

export const inverse = iso => (F, xi2yF, x, i) =>
Expand Down
1 change: 1 addition & 0 deletions test/core.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,5 +122,6 @@ export const getInverse = R.curry((i, s) => set(i, s, undefined))

export const iso = lens

export const fromClass = L.fromClass
export const identity = iso(R.identity, R.identity)
export const inverse = i => iso(getInverse(i), get(i))
11 changes: 11 additions & 0 deletions test/tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -535,6 +535,17 @@ describe("L.branch", () => {
testEq('L.set(L.branch({a: ["x",0], b: []}), 0, null)', {a:{x:[0]},b:0})
})

function XYZ(x,y,z) {
this.x = x
this.y = y
this.z = z
}

describe("L.fromClass", () => {
testEq('L.get([L.fromClass(XYZ), "y"], new XYZ(1,2,3))', 2)
testEq('L.set([L.fromClass(XYZ), "x"], -1, new XYZ(1,2,3))', new XYZ(-1,2,3))
})

describe("indexing", () => {
testEq('L.modify(L.identity, (x, i) => [typeof x, typeof i], 0)',
["number", "undefined"])
Expand Down
1 change: 1 addition & 0 deletions test/types.js
Original file line number Diff line number Diff line change
Expand Up @@ -148,5 +148,6 @@ export const iso = T.fn([T.fn([T_maybeData], T_maybeData),
T.fn([T_maybeData], T_maybeData)],
T_isomorphism)

export const fromClass = T.fn([T.any], T_isomorphism)
export const identity = T_isomorphism
export const inverse = T.fn([T_isomorphism], T_isomorphism)

0 comments on commit b497394

Please sign in to comment.