Skip to content

Commit

Permalink
Support IComputedOptions in createTransformer
Browse files Browse the repository at this point in the history
In the same vain as #215, it would be great to use a custom equals
function with createTransformer, to avoid bubbling bubbling recomputes
of transformers that return arrays.

This commit passes the options through to the internal `computed`.  The
name option is not passed through, since that can be changed with
the `debugNameGenerator` option.
  • Loading branch information
samdroid-apps committed Oct 23, 2019
1 parent c0e5c93 commit 43805db
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
15 changes: 10 additions & 5 deletions src/create-transformer.ts
@@ -1,12 +1,14 @@
import { computed, onBecomeUnobserved, IComputedValue } from "mobx"
import { computed, onBecomeUnobserved, IComputedValue, IComputedValueOptions } from "mobx"
import { invariant, addHiddenProp } from "./utils"

export type ITransformer<A, B> = (object: A) => B

export interface ITransformerParams<A, B> {
onCleanup?: (resultObject: B | undefined, sourceObject?: A) => void
debugNameGenerator?: (sourceObject?: A) => string
}
export type ITransformerParams<A, B> =
| {
onCleanup?: (resultObject: B | undefined, sourceObject?: A) => void
debugNameGenerator?: (sourceObject?: A) => string
}
| Exclude<IComputedValueOptions<B>, "name">

let memoizationId = 0

Expand Down Expand Up @@ -40,9 +42,11 @@ export function createTransformer<A, B>(

function createView(sourceIdentifier: number, sourceObject: A) {
let latestValue: B
let computedValueOptions = {}
if (typeof arg2 === "object") {
onCleanup = arg2.onCleanup
debugNameGenerator = arg2.debugNameGenerator
computedValueOptions = arg2
} else if (typeof arg2 === "function") {
onCleanup = arg2
} else {
Expand All @@ -57,6 +61,7 @@ export function createTransformer<A, B>(
return (latestValue = transformer(sourceObject))
},
{
...computedValueOptions,
name: prettifiedName
}
)
Expand Down
15 changes: 15 additions & 0 deletions test/create-transformer.ts
Expand Up @@ -1354,3 +1354,18 @@ test("should respect debugNameGenerator argument", () => {
objectName = m.getObserverTree(state, "title").observers[0].name
expect(objectName).toBe("COFFEE-DEBUG")
})

test("supports computed value options", () => {
const events: number[][] = []
const xs = m.observable([1, 2, 3])
const xsLessThan = createTransformer(n => xs.filter(x => x < n), {
equals: m.comparer.structural
})

m.autorun(() => events.push(xsLessThan(3)))
expect(events).toEqual([[1, 2]])

events.length = 0
xs.push(4)
expect(events).toEqual([])
})

0 comments on commit 43805db

Please sign in to comment.