Code Organization Patterns
Module-Like Objects
Objects can group related helper functions when a small program does not need separate files.
module object
A module-like object keeps related values and functions under one clear name.
Module-Like Objects
module.ts
Replay: real traced execution (multi-file project)
type FormatMode = "short" | "long";
const LessonTools = {
title(name: string): string {
return name.trim().toUpperCase();
},
format(name: string, mode: FormatMode): string {
const title: string = this.title(name);
return mode === "long" ? `Lesson: ${title}` : title;
},
};
const mode: FormatMode = "short";
const label: string = LessonTools.format(" typescript ", mode);
console.log(label);
type FormatMode = "short" | "long";
const LessonTools = {
title(name: string): string {
return name.trim().toUpperCase();
},
format(name: string, mode: FormatMode): string {
const title: string = this.title(name);
return mode === "long" ? `Lesson: ${title}` : title;
},
};
const mode: FormatMode = "long";
const label: string = LessonTools.format(" typescript ", mode);
console.log(label);
LessonTools ← [object Object], mode ← short, label ← TYPESCRIPT
1type FormatMode = "short" | "long";23const LessonTools→ [object Object] = {4 title(name: string): string {5 return name.trim().toUpperCase();6 },7 format(name: string, mode: FormatMode): string {8 const title: string = this.title(name);9 return mode === "long" ? `Lesson: ${title}` : title;10 },11};1213const mode→ short: FormatMode = "short"; //@mode="long"14const label→ TYPESCRIPT: string = LessonTools.format(" typescript ", modeshort);1516console.log(labelTYPESCRIPT);outputTYPESCRIPT
LessonTools ← [object Object], mode ← long, label ← Lesson: TYPESCRIPT
1type FormatMode = "short" | "long";23const LessonTools→ [object Object] = {4 title(name: string): string {5 return name.trim().toUpperCase();6 },7 format(name: string, mode: FormatMode): string {8 const title: string = this.title(name);9 return mode === "long" ? `Lesson: ${title}` : title;10 },11};1213const mode→ long: FormatMode = "long";14const label→ Lesson: TYPESCRIPT: string = LessonTools.format(" typescript ", modelong);1516console.log(labelLesson: TYPESCRIPT);outputLesson: TYPESCRIPT