fuzzyworld

tools / files / cheatsheets / apps / index.ts

index.ts

5.1 KB · history · blame

1const a = 1;
2const b = 2;
3const c = a + b;
4console.log({ a, b, c });
5
6const getUserInput1 = (): string | undefined => {
7 return "User Input";
8};
9const getUserInput2 = (): number | number[] => {
10 return [1, 2, 3];
11};
12
13const input1 = getUserInput1();
14console.log(`1, type of input1: ${typeof input1}`);
15if (typeof input1 === "string") {
16 console.log("2, input1 is a string:", input1);
17}
18
19const input2 = getUserInput2();
20console.log(`3, type of input2: ${typeof input2}`);
21if (input2 instanceof Array) {
22 console.log("4, input2 is an array:", input2);
23}
24
25console.log(`5, done with type checks`);
26
27const typeString: string = "This is a string";
28const typeNumber: number = 42;
29const typeBoolean: boolean = true;
30const typeUndefined: undefined = undefined;
31const typeNull: null = null;
32const typeVoid: void = undefined; // void is often used for functions that do not return a value
33const typeUnknown: unknown = "This could be anything";
34
35console.log(`6, done with type checks`);
36
37const stringArray: string[] = ["apple", "banana", "cherry"];
38const numberArray: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
39if (Array.isArray(stringArray)) {
40 console.log("7, typeStringArray is an array:", stringArray);
41}
42if (Array.isArray(numberArray)) {
43 console.log("8, typeNumberArray is an array:", numberArray);
44}
45
46let subNumArray: number[] = numberArray.slice(1, 6); // Get a sub-array from index 1 to 5 (not including index 6)
47console.log(`8.1, subNumArray:`, subNumArray);
48subNumArray.push(11); // Add 11 to the end of the array
49subNumArray = subNumArray.filter(num => num % 2 === 0); // Filter even numbers
50subNumArray.splice(2, 1, 12); // Replace the third element with 12
51subNumArray.shift(); // Remove the first element
52subNumArray = subNumArray.concat([13, 14]); // Concatenate with another array
53const arraySum = subNumArray.reduce((sum, curr) => sum + curr, 0); // Sum of elements
54console.log(`8.2, arraySum:`, arraySum);
55console.log(`8.3, subNumArray after changes:`, subNumArray);
56
57const namedFields: { id: number } = { id: 1 };
58if ("id" in namedFields) {
59 console.log("9, typeNamedFields has an id field:", namedFields.id);
60}
61
62const object: { id: number; name: string } = { id: 1, name: "Object Name" };
63console.log(`10, typeObject:`, object);
64console.log(`11, typeof typeObject:`, typeof object);
65
66const fn = (param: string): number => { return param.length; };
67console.log(`12, typeFunction:`, fn);
68console.log(`13, typeof typeFunction:`, typeof fn);
69console.log(`14, typeFunction result:`, fn("Hello"));
70
71const tuple: [number, string] = [1, "Tuple"];
72console.log(`15, typeTuple:`, tuple);
73console.log(`16, typeof typeTuple:`, typeof tuple);
74
75const now = new Date();
76console.log(`17, Current Date:`, now);
77console.log(`18, typeof now:`, typeof now);
78
79const yesterdayGD = new Date(now);
80yesterdayGD.setDate(now.getDate() - 1);
81console.log(`19, Yesterday's Date (using getDate()):`, yesterdayGD);
82
83const yesterdayGT = new Date(now.getTime() - 24 * 60 * 60 * 1000);
84console.log(`20, Yesterday's Date (using getTime()):`, yesterdayGT);
85
86const durationMs = now.getTime() - yesterdayGD.getTime();
87console.log(`21, Duration in milliseconds:`, durationMs);
88
89const map: Map<string, number> = new Map([
90 ["a", 1],
91 ["b", 2],
92 ["c", 3]
93]);
94console.log(`22, map:`, map);
95
96map.set("d", 4);
97map.set("b", 5);
98map.delete("c");
99map.get("a");
100console.log(`23, map after modifications:`, map);
101map.clear();
102
103const set: Set<number> = new Set([1, 2, 3]);
104console.log(`24, set:`, set);
105set.add(4);
106set.add(2); // Duplicate, will not be added
107set.delete(1);
108set.has(3);
109set.size;
110console.log(`25, set after modifications:`, set);
111
112const regex = /p=(\d+),(\d+) v=(-?\d+),(-?\d+)/;
113const match = regex.exec("p=1,2 v=-3,4")!;
114const pos = {
115 x: parseInt(match[1]!, 10),
116 y: parseInt(match[2]!, 10)
117};
118const vel = {
119 x: parseInt(match[3]!, 10),
120 y: parseInt(match[4]!, 10)
121};
122
123interface Info {
124 id: number;
125 name: string;
126 coords: {
127 x: number;
128 y: number;
129 };
130 expiration?: Date;
131 tags: string[] | null;
132
133 getInfo: () => string;
134 findTag(tag: string): boolean;
135
136 get size(): number;
137 set size(value: number | string);
138}
139const info: Info = {
140 id: 1,
141 name: "Info Object",
142 coords: { x: 10, y: 20 },
143 expiration: new Date(),
144 tags: ["tag1", "tag2"],
145
146 getInfo() {
147 return `ID: ${this.id}, Name: ${this.name}, Coords: (${this.coords.x}, ${this.coords.y})`;
148 },
149
150 findTag(tag: string): boolean {
151 return this.tags ? this.tags.includes(tag) : false;
152 },
153
154 get size(): number {
155 return this.tags ? this.tags.length : 0;
156 },
157 set size(value: number | string) {
158 if (typeof value === "number") {
159 this.tags = Array(value).fill("defaultTag");
160 } else if (typeof value === "string") {
161 this.tags = [value];
162 }
163 }
164};
165info.size = 3; // Set size to 3, will fill with default tags
166console.log(`26, info:`, info);
167console.log(`27, info.getInfo():`, info.getInfo());
168console.log(`28, info.get size:`, info.size);
169
170interface DataSource<ResponseType> {
171 fetchData(): ResponseType;
172}
173
174interface DataSource2<ResponseType extends { status: number }> {
175 fetchData(): ResponseType;
176}