I have a task to create a method decorator that ensures a decorated method is only executed once.
Here's an example:
class Example {
data: any;
@executeOnce
setData(newData: any) {
this.newData = newData;
}
}
const example = new Example();
example.setData([1,2,3]);
console.log(example.data); // [1,2,3]
example.setData('new string');
console.log(example.data); // [1,2,3]
I've been trying different approaches to prevent a function from being called twice without success. My unit tests are failing as well. Here's what I have so far:
const executeOnce = (
target: Object,
propertyKey: string | symbol,
descriptor: PropertyDescriptor
) => {
const method = descriptor.value;
descriptor.value = function (...args){
// ???
}
};
Unit tests:
describe('executeOnce', () => {
it('should execute method once with single argument', () => {
class Test {
data: string;
@executeOnce
setData(newData: string) {
this.data = newData;
}
}
const test = new Test();
test.setData('first string');
test.setData('second string');
assert.strictEqual(test.data, 'first string')
});
it('should execute method once with multiple arguments', () => {
class Test {
user: {name: string, age: number};
@executeOnce
setUser(name: string, age: number) {
this.user = {name, age};
}
}
const test = new Test();
test.setUser('John',22);
test.setUser('Bill',34);
assert.deepStrictEqual(test.user, {name: 'John', age: 22})
});
it('should always return the result of the first execution', () => {
class Test {
@executeOnce
sayHello(name: string) {
return `Hello ${name}!`;
}
}
const test = new Test();
test.sayHello('John');
test.sayHello('Mark');
assert.strictEqual(test.sayHello('new name'), 'Hello John!')
})
});
Can you offer me some assistance? Thank you in advance!