Skip to content

Commit

Permalink
Bugfix of internal state of @lazy
Browse files Browse the repository at this point in the history
  • Loading branch information
mlhaufe committed Oct 26, 2020
1 parent ed00c0e commit 7b5ad11
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 8 deletions.
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@final-hill/class-tools",
"version": "1.2.1",
"version": "1.2.2",
"description": "Class Tools provides a number of utility functions and decorators to ease the use of features commonly found in functional languages",
"main": "dist/index.js",
"scripts": {
Expand Down
6 changes: 5 additions & 1 deletion src/lazy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,12 @@ describe('@lazy', () => {
}

const alt = new Foo(() => 10, () => 20);

expect(alt.left).toBe(10);
expect(alt.right).toBe(20);

// test internal state of @lazy
const alt2 = new Foo(() => 30, () => 40);
expect(alt2.left).toBe(30);
expect(alt2.right).toBe(40);
});
});
15 changes: 10 additions & 5 deletions src/lazy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,20 @@ function lazy(
assert(descriptor.get != undefined, '@lazy can only be applied to a getter');
assert(descriptor.set == undefined, 'a setter can not be defined when using @lazy');

const initializer = descriptor.get;

let _private: any;
const initializer = descriptor.get,
_private = new WeakMap();

/**
* The new getter
* @param {this} this - The target
* @returns {any} -
*/
function get(this: typeof target): any {
return _private ?? set.call(this, initializer.call(this));
if(_private.has(this)) {
return _private.get(this);
} else {
return set.call(this, initializer.call(this));
}
}

/**
Expand All @@ -43,7 +46,9 @@ function lazy(
* @returns {any} - The assigned value
*/
function set(this: typeof target, value: any): any {
return _private = value;
_private.set(this,value);

return value;
}

return { get, set };
Expand Down

0 comments on commit 7b5ad11

Please sign in to comment.