Skip to content

Instantly share code, notes, and snippets.

@luizcalaca
Last active June 3, 2023 18:30
Show Gist options
  • Select an option

  • Save luizcalaca/72869043b481affcd446ee0e8fe8cfc8 to your computer and use it in GitHub Desktop.

Select an option

Save luizcalaca/72869043b481affcd446ee0e8fe8cfc8 to your computer and use it in GitHub Desktop.
Reversing a string using Typescript with Decorators
// Decorator de split
function splitDecorator(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function (str: string) {
const arr = str.split('');
return originalMethod.apply(this, [arr]);
};
return descriptor;
}
// Decorator de reverse
function reverseDecorator(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function (arr: string[]) {
const reversedArr = arr.reverse();
return originalMethod.apply(this, [reversedArr]);
};
return descriptor;
}
// Decorator de join
function join(char: string) {
return function joinDecorator(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function (arr: string[]) {
const joinedString = arr.join(char);
return originalMethod.apply(this, [joinedString]);
};
return descriptor;
}
}
class StringReverser {
@splitDecorator
@reverseDecorator
@join('')
reverseString(str: string): string {
return str;
}
}
const stringReverser = new StringReverser();
console.log(stringReverser.reverseString('Hello, World!'));
@luizcalaca
Copy link
Author

Remember that is necessary to enable 'experimentalDecorators' in tsconfig.json

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment