Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add: menambahkan materi Decorators di TypescriptBasic #29

Draft
wants to merge 7 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions TypeScriptBasic/0x_Decorators/Decorators.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { StringUtility } from './Decorators';

test('[TypeScriptBasic/0x_Decorators] Pengecekan Class Decorator', () => {
expect(new StringUtility(['Test']).data[0]).toBe('Teks pengganti argumen pertama');
});

test('[TypeScriptBasic/0x_Decorators] Pengecekan Method Decorator', () => {
expect(() => new StringUtility(['Test']).sambungData(123 as unknown as string)).toThrowError();
});
39 changes: 39 additions & 0 deletions TypeScriptBasic/0x_Decorators/Decorators.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// Penjelasan akan ditulis nanti.

function gantiArgumenConstructor(constructor: typeof StringUtility): typeof StringUtility {
return class extends constructor {
constructor(args: string[]) {
super(['Teks pengganti argumen pertama', ...args]);
}
};
}

function cekArgumen(target: StringUtility, key: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function (...args: unknown[]) {
if (args.some(arg => typeof arg !== 'string')) throw Error('Argumen harus berupa string');
return originalMethod.apply(this, [args[0], ...args.slice(1)]);
};
}

@gantiArgumenConstructor
class StringUtility {
public data: string[];

constructor(data: string[]) {
this.data = data;
}

@cekArgumen
sambungData(separator: string): string {
return this.data.join(separator);
}

get dataKapital(): string[] {
return this.data.map(data => data.toUpperCase());
}
}

export {
StringUtility
};
3 changes: 3 additions & 0 deletions babel.config.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
module.exports = {
plugins: [
[require('@babel/plugin-proposal-decorators').default, { legacy: true }]
],
presets: [
['@babel/preset-env', {targets: {node: 'current'}}],
'@babel/preset-typescript',
Expand Down
Loading