Skip to content

Commit

Permalink
feat: menambahkan file materi decorator
Browse files Browse the repository at this point in the history
  • Loading branch information
Mednoob committed Mar 11, 2022
1 parent 3321b00 commit e30e481
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
14 changes: 14 additions & 0 deletions TypeScriptBasic/0x_Decorators/Decorators.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
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 Property Decorator", () => {
// @ts-expect-error
expect(new StringUtility("abc")).toThrowError();
})

test("[TypeScriptBasic/0x_Decorators] Pengecekan Method Decorator", () => {
expect(StringUtility.prototype.sambungData = () => { return "" }).toThrowError();
})
44 changes: 44 additions & 0 deletions TypeScriptBasic/0x_Decorators/Decorators.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// Penjelasan akan ditulis nanti.

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

function buatMethodTidakDapatDiubah(target: any, key: string, descriptor: PropertyDescriptor) {
descriptor.writable = false;
}

function harusBerupaArray(target: any, key: string) {
if (!Array.isArray(target[key])) {
throw new Error(`${key} harus berupa array`);
}
}

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

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

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

// Bisa digunakan juga pada accessor property
@buatMethodTidakDapatDiubah
get dataKapital(): string[] {
return this.data.map(data => data.toUpperCase());
}
}

export {
StringUtility
}

0 comments on commit e30e481

Please sign in to comment.