Skip to content

Commit

Permalink
Protect against improper use in classes
Browse files Browse the repository at this point in the history
Fixes #8
  • Loading branch information
sindresorhus committed Nov 15, 2023
1 parent 2872fb8 commit 95eef87
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
4 changes: 4 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ function debounce(function_, wait = 100, immediate) {
}

const debounced = function (...arguments_) {
if (storedContext && this !== storedContext) {
throw new Error('Debounced method called with different contexts.');
}

storedContext = this; // eslint-disable-line unicorn/no-this-assignment
storedArguments = arguments_;
timestamp = Date.now();
Expand Down
25 changes: 25 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -173,3 +173,28 @@ describe('forcing execution', () => {
expect(callback.args[2]).toEqual([1]);
});
});

describe('context check in debounced function', () => {
it('should throw an error if debounced method is called with different contexts', () => {
function MyClass() {}

MyClass.prototype.debounced = debounce(() => {});

const instance1 = new MyClass();
const instance2 = new MyClass();

// Call the debounced function on the first instance
instance1.debounced();

let errorThrown = false;
try {
// Attempt to call the same debounced function on a different instance
instance2.debounced();
} catch (error) {
errorThrown = true;
expect(error.message).toEqual('Debounced method called with different contexts.');
}

expect(errorThrown).toBeTruthy();
});
});

0 comments on commit 95eef87

Please sign in to comment.