diff --git a/package-lock.json b/package-lock.json index c26e838..fdd010b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "@final-hill/class-tools", - "version": "1.2.1", + "version": "1.2.2", "lockfileVersion": 1, "requires": true, "dependencies": { diff --git a/package.json b/package.json index 5f9731b..100057e 100644 --- a/package.json +++ b/package.json @@ -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": { diff --git a/src/lazy.test.ts b/src/lazy.test.ts index 918e19b..39d9b4d 100644 --- a/src/lazy.test.ts +++ b/src/lazy.test.ts @@ -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); }); }); \ No newline at end of file diff --git a/src/lazy.ts b/src/lazy.ts index 20e649d..3735726 100644 --- a/src/lazy.ts +++ b/src/lazy.ts @@ -23,9 +23,8 @@ 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 @@ -33,7 +32,11 @@ function lazy( * @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)); + } } /** @@ -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 };