Pass internal this through on objectProperties (#1610)

* Pass internal this through on objectProperties

* Fix property test
This commit is contained in:
Jaco
2022-07-19 22:03:26 +03:00
committed by GitHub
parent f41519e185
commit 306bbdea12
2 changed files with 8 additions and 6 deletions
+2 -2
View File
@@ -128,7 +128,7 @@ describe('objectProperty/objectProperties', (): void => {
expect(getter).not.toHaveBeenCalled();
expect(test.a).toEqual(123);
expect(getter).toHaveBeenCalledWith('a');
expect(getter).toHaveBeenCalledWith('a', expect.objectContaining({}));
});
it('calls back with the key name & index (numtiple)', (): void => {
@@ -139,7 +139,7 @@ describe('objectProperty/objectProperties', (): void => {
expect(getter).not.toHaveBeenCalled();
expect(test.b).toEqual(123);
expect(getter).toHaveBeenCalledWith('b', 1);
expect(getter).toHaveBeenCalledWith('b', 1, expect.objectContaining({}));
});
perf('objectProperties (obj)', 50_000, [[]], () => objectProperties({}, ['foo', 'bar', 'baz'], (k) => k));
+6 -4
View File
@@ -5,7 +5,7 @@
* @name objectProperty
* @summary Assign a get property on the input object
*/
export function objectProperty (that: object, key: string, getter: (k: string) => unknown): void {
export function objectProperty <T> (that: object, key: string, getter: (k: string, self: T) => unknown): void {
// There are 3 approaches here -
// - Object.prototype.hasOwnProperty.call(that, key) - this only checks the current class, i.e
// will retuirn false if the property is set in the parent class
@@ -17,7 +17,9 @@ export function objectProperty (that: object, key: string, getter: (k: string) =
enumerable: true,
// Unlike in lazy, we always call into the upper function, i.e. this method
// does not cache old values (it is expected to be used for dynamic values)
get: () => getter(key)
get: function (): unknown {
return getter(key, this as unknown as T);
}
});
}
}
@@ -26,8 +28,8 @@ export function objectProperty (that: object, key: string, getter: (k: string) =
* @name objectProperties
* @summary Assign get properties on the input object
*/
export function objectProperties (that: object, keys: string[], getter: (k: string, i: number) => unknown): void {
export function objectProperties <T> (that: object, keys: string[], getter: (k: string, i: number, self: T) => unknown): void {
for (let i = 0; i < keys.length; i++) {
objectProperty(that, keys[i], (k) => getter(k, i));
objectProperty(that, keys[i], (k, self) => getter(k, i, self as T));
}
}