Last active
June 3, 2023 18:30
-
-
Save luizcalaca/72869043b481affcd446ee0e8fe8cfc8 to your computer and use it in GitHub Desktop.
Reversing a string using Typescript with Decorators
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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!')); | |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Remember that is necessary to enable 'experimentalDecorators' in tsconfig.json