Skip to content

Commit

Permalink
Merge 'pull-920': primitives as memoization key
Browse files Browse the repository at this point in the history
  • Loading branch information
Andrey Kogut authored and mweststrate committed Apr 3, 2017
2 parents 6385faf + 5edbcbc commit 2c3921c
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 3 deletions.
6 changes: 4 additions & 2 deletions src/api/createtransformer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,14 @@ export function createTransformer<A, B>(transformer: ITransformer<A, B>, onClean
}

function getMemoizationId(object) {
if(typeof object === 'string' || typeof object === 'number')
return object
if (object === null || typeof object !== "object")
throw new Error("[mobx] transform expected some kind of object, got: " + object);
throw new Error("[mobx] transform expected some kind of object or primitive value, got: " + object);
let tid = object.$transformId;
if (tid === undefined) {
tid = getNextId();
addHiddenProp(object, "$transformId", tid);
}
return tid;
}
}
51 changes: 50 additions & 1 deletion test/transform.js
Original file line number Diff line number Diff line change
Expand Up @@ -1003,4 +1003,53 @@ test('transform tree (dynamic tags - peek / rebuild)', function(t) {
t.deepEqual(state.renderedNodes.length, 0);

t.end();
});
});

// https://github.com/mobxjs/mobx/issues/886
test('transform with primitive key', function(t) {
m.extras.resetGlobalState();

function Bob() {
this.num = Math.floor(Math.random() * 1000);
m.extendObservable(this, {
get name() {
return 'Bob' + this.num;
}
});
}

var observableBobs = m.observable([]);
var bobs = [];

var bobFactory = m.createTransformer(function(key) {
return new Bob();
});

m.autorun(function() {
bobs = observableBobs.map(function(bob) {
return bobFactory(bob);
});
});

observableBobs.push('Bob1');
observableBobs.push('Bob1');
t.equal(bobs[0].name, bobs[1].name);

observableBobs.clear();
observableBobs.push('Bob1');
observableBobs.push('Bob2');
t.notEqual(bobs[0].name, bobs[1].name);

observableBobs.clear();
observableBobs.push(1);
observableBobs.push(1);
t.equal(bobs[0].name, bobs[1].name);

observableBobs.clear();
observableBobs.push(1);
observableBobs.push(2);
t.notEqual(bobs[0].name, bobs[1].name);

t.end();
});

0 comments on commit 2c3921c

Please sign in to comment.