Skip to content

Commit 205fd8f

Browse files
authoredSep 9, 2024··
Fix the class context validation (#43)
1 parent 312a06e commit 205fd8f

File tree

2 files changed

+31
-10
lines changed

2 files changed

+31
-10
lines changed
 

‎index.js

+6-2
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,12 @@ function debounce(function_, wait = 100, options = {}) {
4040
}
4141

4242
const debounced = function (...arguments_) {
43-
if (storedContext && this !== storedContext) {
44-
throw new Error('Debounced method called with different contexts.');
43+
if (
44+
storedContext
45+
&& this !== storedContext
46+
&& Object.getPrototypeOf(this) === Object.getPrototypeOf(storedContext)
47+
) {
48+
throw new Error('Debounced method called with different contexts of the same prototype.');
4549
}
4650

4751
storedContext = this; // eslint-disable-line unicorn/no-this-assignment

‎test.js

+25-8
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,7 @@ test('forcing execution', async t => {
147147
});
148148

149149
test('context check in debounced function', async t => {
150-
await t.test('should throw an error if debounced method is called with different contexts', async () => {
150+
await t.test('should throw an error if debounced method is called with different contexts of the same class', async () => {
151151
function MyClass() {}
152152

153153
MyClass.prototype.debounced = debounce(() => {});
@@ -157,15 +157,32 @@ test('context check in debounced function', async t => {
157157

158158
instance1.debounced();
159159

160-
let errorThrown = false;
161-
try {
160+
assert.throws(() => {
162161
instance2.debounced();
163-
} catch (error) {
164-
errorThrown = true;
165-
assert.strictEqual(error.message, 'Debounced method called with different contexts.', 'Error message should match');
166-
}
162+
}, {
163+
message: 'Debounced method called with different contexts of the same prototype.',
164+
}, 'An error should have been thrown');
165+
});
166+
167+
await t.test('should not throw an error if debounced method is called with different contexts of different classes', async () => {
168+
function MyClass1() {}
169+
function MyClass2() {}
170+
171+
const debouncedFunction = debounce(() => {});
172+
173+
MyClass1.prototype.debounced = debouncedFunction;
174+
MyClass2.prototype.debounced = debouncedFunction;
167175

168-
assert.ok(errorThrown, 'An error should have been thrown');
176+
const instance1 = new MyClass1();
177+
const instance2 = new MyClass2();
178+
179+
instance1.debounced();
180+
181+
assert.doesNotThrow(() => {
182+
instance2.debounced();
183+
}, {
184+
message: 'Debounced method called with different contexts of the same prototype.',
185+
}, 'An error should not have been thrown');
169186
});
170187
});
171188

0 commit comments

Comments
 (0)
Please sign in to comment.