@sylix/coworker 2.0.10 → 2.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (178) hide show
  1. package/dist/commands/slash/config.d.ts.map +1 -1
  2. package/dist/commands/slash/config.js +23 -5
  3. package/dist/commands/slash/config.js.map +1 -1
  4. package/dist/commands/slash/todo.js +1 -1
  5. package/dist/commands/slash/todo.js.map +1 -1
  6. package/dist/core/CoWorkerAgent.d.ts.map +1 -1
  7. package/dist/core/CoWorkerAgent.js +6 -3
  8. package/dist/core/CoWorkerAgent.js.map +1 -1
  9. package/dist/permissions/PermissionInterceptor.js +1 -1
  10. package/dist/permissions/PermissionInterceptor.js.map +1 -1
  11. package/dist/skills/defaults/accessibility/screen-reader-testing.md +545 -0
  12. package/dist/skills/defaults/accessibility/wcag-audit-patterns.md +555 -0
  13. package/dist/skills/defaults/ai-ml/rag.md +276 -0
  14. package/dist/skills/defaults/backend-development/api-design-principles.md +528 -0
  15. package/dist/skills/defaults/backend-development/api-design.md +285 -0
  16. package/dist/skills/defaults/backend-development/architecture-patterns.md +494 -0
  17. package/dist/skills/defaults/backend-development/async-python.md +237 -0
  18. package/dist/skills/defaults/backend-development/auth-implementation-patterns.md +638 -0
  19. package/dist/skills/defaults/backend-development/bazel-build-optimization.md +387 -0
  20. package/dist/skills/defaults/backend-development/billing-automation/SKILL.md +566 -0
  21. package/dist/skills/defaults/backend-development/code-review-excellence.md +538 -0
  22. package/dist/skills/defaults/backend-development/cqrs-implementation.md +554 -0
  23. package/dist/skills/defaults/backend-development/database-design.md +305 -0
  24. package/dist/skills/defaults/backend-development/debugging-strategies.md +536 -0
  25. package/dist/skills/defaults/backend-development/e2e-testing-patterns.md +544 -0
  26. package/dist/skills/defaults/backend-development/error-handling-patterns.md +641 -0
  27. package/dist/skills/defaults/backend-development/fastapi-templates.md +559 -0
  28. package/dist/skills/defaults/backend-development/fastapi.md +309 -0
  29. package/dist/skills/defaults/backend-development/git-advanced-workflows.md +405 -0
  30. package/dist/skills/defaults/backend-development/microservices-patterns.md +595 -0
  31. package/dist/skills/defaults/backend-development/microservices.md +284 -0
  32. package/dist/skills/defaults/backend-development/monorepo-management.md +623 -0
  33. package/dist/skills/defaults/backend-development/nodejs-backend-patterns.md +1048 -0
  34. package/dist/skills/defaults/backend-development/nx-workspace-patterns.md +457 -0
  35. package/dist/skills/defaults/backend-development/paypal-integration/SKILL.md +478 -0
  36. package/dist/skills/defaults/backend-development/pci-compliance/SKILL.md +480 -0
  37. package/dist/skills/defaults/backend-development/python-anti-patterns.md +349 -0
  38. package/dist/skills/defaults/backend-development/python-background-jobs.md +364 -0
  39. package/dist/skills/defaults/backend-development/python-code-style.md +360 -0
  40. package/dist/skills/defaults/backend-development/python-configuration.md +368 -0
  41. package/dist/skills/defaults/backend-development/python-design-patterns.md +296 -0
  42. package/dist/skills/defaults/backend-development/python-error-handling.md +323 -0
  43. package/dist/skills/defaults/backend-development/python-packaging.md +887 -0
  44. package/dist/skills/defaults/backend-development/python-performance-optimization.md +874 -0
  45. package/dist/skills/defaults/backend-development/python-project-structure.md +252 -0
  46. package/dist/skills/defaults/backend-development/python-resilience.md +376 -0
  47. package/dist/skills/defaults/backend-development/python-resource-management.md +421 -0
  48. package/dist/skills/defaults/backend-development/python-type-safety.md +428 -0
  49. package/dist/skills/defaults/backend-development/sql-optimization-patterns.md +509 -0
  50. package/dist/skills/defaults/backend-development/stripe-integration/SKILL.md +522 -0
  51. package/dist/skills/defaults/backend-development/turborepo-caching.md +376 -0
  52. package/dist/skills/defaults/blockchain/defi-protocol-templates.md +430 -0
  53. package/dist/skills/defaults/blockchain/nft-standards.md +364 -0
  54. package/dist/skills/defaults/blockchain/solidity-security.md +514 -0
  55. package/dist/skills/defaults/blockchain/web3-testing.md +360 -0
  56. package/dist/skills/defaults/business/competitive-landscape/SKILL.md +527 -0
  57. package/dist/skills/defaults/business/market-sizing-analysis/SKILL.md +451 -0
  58. package/dist/skills/defaults/business/startup-financial-modeling/SKILL.md +494 -0
  59. package/dist/skills/defaults/business/startup-metrics-framework/SKILL.md +564 -0
  60. package/dist/skills/defaults/business/team-composition-analysis.md +437 -0
  61. package/dist/skills/defaults/compliance/employment-contract-templates/SKILL.md +527 -0
  62. package/dist/skills/defaults/compliance/gdpr-data-handling/SKILL.md +630 -0
  63. package/dist/skills/defaults/data-engineering/airflow-dag-patterns.md +436 -0
  64. package/dist/skills/defaults/data-engineering/airflow.md +519 -0
  65. package/dist/skills/defaults/data-engineering/data-quality.md +583 -0
  66. package/dist/skills/defaults/data-engineering/dbt-transformation-patterns.md +482 -0
  67. package/dist/skills/defaults/data-engineering/dbt.md +556 -0
  68. package/dist/skills/defaults/data-engineering/ml-pipeline-workflow/SKILL.md +247 -0
  69. package/dist/skills/defaults/data-engineering/spark-optimization.md +348 -0
  70. package/dist/skills/defaults/data-engineering/spark.md +411 -0
  71. package/dist/skills/defaults/database/postgresql.md +202 -0
  72. package/dist/skills/defaults/debugging/systematic-debugging.md +249 -0
  73. package/dist/skills/defaults/devops/architecture-decision-records.md +448 -0
  74. package/dist/skills/defaults/devops/changelog-automation.md +580 -0
  75. package/dist/skills/defaults/devops/cicd.md +314 -0
  76. package/dist/skills/defaults/devops/cloud.md +263 -0
  77. package/dist/skills/defaults/devops/code-review-excellence.md +299 -0
  78. package/dist/skills/defaults/devops/cost-optimization.md +295 -0
  79. package/dist/skills/defaults/devops/deployment-pipeline-design.md +356 -0
  80. package/dist/skills/defaults/devops/docker.md +281 -0
  81. package/dist/skills/defaults/devops/git-workflows.md +205 -0
  82. package/dist/skills/defaults/devops/github-actions.md +311 -0
  83. package/dist/skills/defaults/devops/gitlab-ci-patterns.md +266 -0
  84. package/dist/skills/defaults/devops/hybrid-cloud-networking.md +241 -0
  85. package/dist/skills/defaults/devops/istio-traffic-management.md +327 -0
  86. package/dist/skills/defaults/devops/kubernetes.md +339 -0
  87. package/dist/skills/defaults/devops/linkerd-patterns.md +311 -0
  88. package/dist/skills/defaults/devops/multi-cloud-architecture.md +181 -0
  89. package/dist/skills/defaults/devops/observability.md +243 -0
  90. package/dist/skills/defaults/devops/openapi-spec-generation.md +1024 -0
  91. package/dist/skills/defaults/devops/postmortem-writing.md +396 -0
  92. package/dist/skills/defaults/devops/prometheus-configuration.md +265 -0
  93. package/dist/skills/defaults/devops/secrets-management.md +341 -0
  94. package/dist/skills/defaults/devops/service-mesh-observability.md +385 -0
  95. package/dist/skills/defaults/devops/terraform-module-library.md +244 -0
  96. package/dist/skills/defaults/finance/backtesting-frameworks/SKILL.md +663 -0
  97. package/dist/skills/defaults/finance/risk-metrics-calculation/SKILL.md +557 -0
  98. package/dist/skills/defaults/frontend/accessibility-compliance.md +420 -0
  99. package/dist/skills/defaults/frontend/design-system-patterns.md +337 -0
  100. package/dist/skills/defaults/frontend/interaction-design.md +327 -0
  101. package/dist/skills/defaults/frontend/javascript.md +311 -0
  102. package/dist/skills/defaults/frontend/modern-javascript-patterns.md +927 -0
  103. package/dist/skills/defaults/frontend/react-native-design.md +440 -0
  104. package/dist/skills/defaults/frontend/react.md +345 -0
  105. package/dist/skills/defaults/frontend/responsive-design.md +472 -0
  106. package/dist/skills/defaults/frontend/tailwind-design-system.md +337 -0
  107. package/dist/skills/defaults/frontend/typescript-advanced-types.md +724 -0
  108. package/dist/skills/defaults/frontend/typescript.md +334 -0
  109. package/dist/skills/defaults/frontend/visual-design-foundations.md +326 -0
  110. package/dist/skills/defaults/frontend/web-component-design.md +279 -0
  111. package/dist/skills/defaults/game-development/godot-gdscript-patterns.md +188 -0
  112. package/dist/skills/defaults/game-development/unity-ecs-patterns.md +594 -0
  113. package/dist/skills/defaults/kubernetes/gitops-workflow.md +285 -0
  114. package/dist/skills/defaults/kubernetes/gitops.md +280 -0
  115. package/dist/skills/defaults/kubernetes/helm-chart-scaffolding.md +553 -0
  116. package/dist/skills/defaults/kubernetes/helm.md +343 -0
  117. package/dist/skills/defaults/kubernetes/k8s-manifest-generator.md +501 -0
  118. package/dist/skills/defaults/kubernetes/k8s-security-policies.md +342 -0
  119. package/dist/skills/defaults/kubernetes/manifests.md +330 -0
  120. package/dist/skills/defaults/kubernetes/security.md +337 -0
  121. package/dist/skills/defaults/llm-application/embedding-strategies.md +608 -0
  122. package/dist/skills/defaults/llm-application/hybrid-search-implementation.md +570 -0
  123. package/dist/skills/defaults/llm-application/hybrid-search.md +570 -0
  124. package/dist/skills/defaults/llm-application/langchain-architecture.md +666 -0
  125. package/dist/skills/defaults/llm-application/langchain.md +259 -0
  126. package/dist/skills/defaults/llm-application/llm-evaluation.md +695 -0
  127. package/dist/skills/defaults/llm-application/prompt-engineering-patterns.md +449 -0
  128. package/dist/skills/defaults/llm-application/prompt-engineering.md +219 -0
  129. package/dist/skills/defaults/llm-application/rag-implementation.md +434 -0
  130. package/dist/skills/defaults/llm-application/similarity-search-patterns.md +560 -0
  131. package/dist/skills/defaults/llm-application/similarity-search.md +560 -0
  132. package/dist/skills/defaults/llm-application/vector-index-tuning.md +523 -0
  133. package/dist/skills/defaults/mobile/mobile-android-design.md +440 -0
  134. package/dist/skills/defaults/mobile/mobile-ios-design.md +266 -0
  135. package/dist/skills/defaults/monitoring/distributed-tracing.md +436 -0
  136. package/dist/skills/defaults/monitoring/grafana-dashboards.md +370 -0
  137. package/dist/skills/defaults/monitoring/prometheus-configuration.md +379 -0
  138. package/dist/skills/defaults/monitoring/slo-implementation.md +323 -0
  139. package/dist/skills/defaults/refactoring/code-refactoring.md +349 -0
  140. package/dist/skills/defaults/security/anti-reversing-techniques/SKILL.md +559 -0
  141. package/dist/skills/defaults/security/auditor.md +168 -0
  142. package/dist/skills/defaults/security/binary-analysis-patterns/SKILL.md +438 -0
  143. package/dist/skills/defaults/security/memory-forensics/SKILL.md +483 -0
  144. package/dist/skills/defaults/security/mtls-configuration.md +349 -0
  145. package/dist/skills/defaults/security/protocol-reverse-engineering/SKILL.md +520 -0
  146. package/dist/skills/defaults/security/sast-configuration.md +182 -0
  147. package/dist/skills/defaults/security/security.md +313 -0
  148. package/dist/skills/defaults/security/stride-analysis.md +273 -0
  149. package/dist/skills/defaults/security/threat-mitigation-mapping.md +290 -0
  150. package/dist/skills/defaults/systems/bash-defensive-patterns/SKILL.md +539 -0
  151. package/dist/skills/defaults/systems/bats-testing-patterns/SKILL.md +631 -0
  152. package/dist/skills/defaults/systems/go-concurrency-patterns.md +657 -0
  153. package/dist/skills/defaults/systems/memory-safety-patterns.md +605 -0
  154. package/dist/skills/defaults/systems/rust-async-patterns.md +519 -0
  155. package/dist/skills/defaults/systems/shellcheck-configuration/SKILL.md +456 -0
  156. package/dist/skills/defaults/team-collaboration/multi-reviewer-patterns.md +126 -0
  157. package/dist/skills/defaults/team-collaboration/parallel-feature-development.md +151 -0
  158. package/dist/skills/defaults/testing/javascript-testing-patterns.md +1021 -0
  159. package/dist/skills/defaults/testing/python-testing-patterns.md +351 -0
  160. package/dist/skills/defaults/testing/testing.md +332 -0
  161. package/dist/skills/defaults/workflows/context-driven-development.md +384 -0
  162. package/dist/skills/defaults/workflows/track-management.md +592 -0
  163. package/dist/skills/defaults/workflows/workflow-patterns.md +622 -0
  164. package/dist/skills/index.d.ts +11 -0
  165. package/dist/skills/index.d.ts.map +1 -0
  166. package/dist/skills/index.js +129 -0
  167. package/dist/skills/index.js.map +1 -0
  168. package/dist/utils/character.js +6 -9
  169. package/dist/utils/character.js.map +1 -1
  170. package/dist/utils/contextManager.js +3 -7
  171. package/dist/utils/contextManager.js.map +1 -1
  172. package/dist/utils/inputbar.d.ts.map +1 -1
  173. package/dist/utils/inputbar.js +8 -1
  174. package/dist/utils/inputbar.js.map +1 -1
  175. package/dist/utils/output.d.ts.map +1 -1
  176. package/dist/utils/output.js +3 -35
  177. package/dist/utils/output.js.map +1 -1
  178. package/package.json +1 -1
@@ -0,0 +1,927 @@
1
+ ---
2
+ name: modern-javascript-patterns
3
+ description: Master ES6+ features including async/await, destructuring, spread operators, arrow functions, promises, modules, iterators, generators, and functional programming patterns for writing clean, efficient JavaScript code.
4
+ ---
5
+
6
+ # Modern JavaScript Patterns
7
+
8
+ Comprehensive guide for mastering modern JavaScript (ES6+) features, functional programming patterns, and best practices for writing clean, maintainable, and performant code.
9
+
10
+ ## When to Use This Skill
11
+
12
+ - Refactoring legacy JavaScript to modern syntax
13
+ - Implementing functional programming patterns
14
+ - Optimizing JavaScript performance
15
+ - Writing maintainable and readable code
16
+ - Working with asynchronous operations
17
+ - Building modern web applications
18
+ - Migrating from callbacks to Promises/async-await
19
+ - Implementing data transformation pipelines
20
+
21
+ ## ES6+ Core Features
22
+
23
+ ### 1. Arrow Functions
24
+
25
+ **Syntax and Use Cases:**
26
+
27
+ ```javascript
28
+ // Traditional function
29
+ function add(a, b) {
30
+ return a + b;
31
+ }
32
+
33
+ // Arrow function
34
+ const add = (a, b) => a + b;
35
+
36
+ // Single parameter (parentheses optional)
37
+ const double = (x) => x * 2;
38
+
39
+ // No parameters
40
+ const getRandom = () => Math.random();
41
+
42
+ // Multiple statements (need curly braces)
43
+ const processUser = (user) => {
44
+ const normalized = user.name.toLowerCase();
45
+ return { ...user, name: normalized };
46
+ };
47
+
48
+ // Returning objects (wrap in parentheses)
49
+ const createUser = (name, age) => ({ name, age });
50
+ ```
51
+
52
+ **Lexical 'this' Binding:**
53
+
54
+ ```javascript
55
+ class Counter {
56
+ constructor() {
57
+ this.count = 0;
58
+ }
59
+
60
+ // Arrow function preserves 'this' context
61
+ increment = () => {
62
+ this.count++;
63
+ };
64
+
65
+ // Traditional function loses 'this' in callbacks
66
+ incrementTraditional() {
67
+ setTimeout(function () {
68
+ this.count++; // 'this' is undefined
69
+ }, 1000);
70
+ }
71
+
72
+ // Arrow function maintains 'this'
73
+ incrementArrow() {
74
+ setTimeout(() => {
75
+ this.count++; // 'this' refers to Counter instance
76
+ }, 1000);
77
+ }
78
+ }
79
+ ```
80
+
81
+ ### 2. Destructuring
82
+
83
+ **Object Destructuring:**
84
+
85
+ ```javascript
86
+ const user = {
87
+ id: 1,
88
+ name: "John Doe",
89
+ email: "john@example.com",
90
+ address: {
91
+ city: "New York",
92
+ country: "USA",
93
+ },
94
+ };
95
+
96
+ // Basic destructuring
97
+ const { name, email } = user;
98
+
99
+ // Rename variables
100
+ const { name: userName, email: userEmail } = user;
101
+
102
+ // Default values
103
+ const { age = 25 } = user;
104
+
105
+ // Nested destructuring
106
+ const {
107
+ address: { city, country },
108
+ } = user;
109
+
110
+ // Rest operator
111
+ const { id, ...userWithoutId } = user;
112
+
113
+ // Function parameters
114
+ function greet({ name, age = 18 }) {
115
+ console.log(`Hello ${name}, you are ${age}`);
116
+ }
117
+ greet(user);
118
+ ```
119
+
120
+ **Array Destructuring:**
121
+
122
+ ```javascript
123
+ const numbers = [1, 2, 3, 4, 5];
124
+
125
+ // Basic destructuring
126
+ const [first, second] = numbers;
127
+
128
+ // Skip elements
129
+ const [, , third] = numbers;
130
+
131
+ // Rest operator
132
+ const [head, ...tail] = numbers;
133
+
134
+ // Swapping variables
135
+ let a = 1,
136
+ b = 2;
137
+ [a, b] = [b, a];
138
+
139
+ // Function return values
140
+ function getCoordinates() {
141
+ return [10, 20];
142
+ }
143
+ const [x, y] = getCoordinates();
144
+
145
+ // Default values
146
+ const [one, two, three = 0] = [1, 2];
147
+ ```
148
+
149
+ ### 3. Spread and Rest Operators
150
+
151
+ **Spread Operator:**
152
+
153
+ ```javascript
154
+ // Array spreading
155
+ const arr1 = [1, 2, 3];
156
+ const arr2 = [4, 5, 6];
157
+ const combined = [...arr1, ...arr2];
158
+
159
+ // Object spreading
160
+ const defaults = { theme: "dark", lang: "en" };
161
+ const userPrefs = { theme: "light" };
162
+ const settings = { ...defaults, ...userPrefs };
163
+
164
+ // Function arguments
165
+ const numbers = [1, 2, 3];
166
+ Math.max(...numbers);
167
+
168
+ // Copying arrays/objects (shallow copy)
169
+ const copy = [...arr1];
170
+ const objCopy = { ...user };
171
+
172
+ // Adding items immutably
173
+ const newArr = [...arr1, 4, 5];
174
+ const newObj = { ...user, age: 30 };
175
+ ```
176
+
177
+ **Rest Parameters:**
178
+
179
+ ```javascript
180
+ // Collect function arguments
181
+ function sum(...numbers) {
182
+ return numbers.reduce((total, num) => total + num, 0);
183
+ }
184
+ sum(1, 2, 3, 4, 5);
185
+
186
+ // With regular parameters
187
+ function greet(greeting, ...names) {
188
+ return `${greeting} ${names.join(", ")}`;
189
+ }
190
+ greet("Hello", "John", "Jane", "Bob");
191
+
192
+ // Object rest
193
+ const { id, ...userData } = user;
194
+
195
+ // Array rest
196
+ const [first, ...rest] = [1, 2, 3, 4, 5];
197
+ ```
198
+
199
+ ### 4. Template Literals
200
+
201
+ ```javascript
202
+ // Basic usage
203
+ const name = "John";
204
+ const greeting = `Hello, ${name}!`;
205
+
206
+ // Multi-line strings
207
+ const html = `
208
+ <div>
209
+ <h1>${title}</h1>
210
+ <p>${content}</p>
211
+ </div>
212
+ `;
213
+
214
+ // Expression evaluation
215
+ const price = 19.99;
216
+ const total = `Total: $${(price * 1.2).toFixed(2)}`;
217
+
218
+ // Tagged template literals
219
+ function highlight(strings, ...values) {
220
+ return strings.reduce((result, str, i) => {
221
+ const value = values[i] || "";
222
+ return result + str + `<mark>${value}</mark>`;
223
+ }, "");
224
+ }
225
+
226
+ const name = "John";
227
+ const age = 30;
228
+ const html = highlight`Name: ${name}, Age: ${age}`;
229
+ // Output: "Name: <mark>John</mark>, Age: <mark>30</mark>"
230
+ ```
231
+
232
+ ### 5. Enhanced Object Literals
233
+
234
+ ```javascript
235
+ const name = "John";
236
+ const age = 30;
237
+
238
+ // Shorthand property names
239
+ const user = { name, age };
240
+
241
+ // Shorthand method names
242
+ const calculator = {
243
+ add(a, b) {
244
+ return a + b;
245
+ },
246
+ subtract(a, b) {
247
+ return a - b;
248
+ },
249
+ };
250
+
251
+ // Computed property names
252
+ const field = "email";
253
+ const user = {
254
+ name: "John",
255
+ [field]: "john@example.com",
256
+ [`get${field.charAt(0).toUpperCase()}${field.slice(1)}`]() {
257
+ return this[field];
258
+ },
259
+ };
260
+
261
+ // Dynamic property creation
262
+ const createUser = (name, ...props) => {
263
+ return props.reduce(
264
+ (user, [key, value]) => ({
265
+ ...user,
266
+ [key]: value,
267
+ }),
268
+ { name },
269
+ );
270
+ };
271
+
272
+ const user = createUser("John", ["age", 30], ["email", "john@example.com"]);
273
+ ```
274
+
275
+ ## Asynchronous Patterns
276
+
277
+ ### 1. Promises
278
+
279
+ **Creating and Using Promises:**
280
+
281
+ ```javascript
282
+ // Creating a promise
283
+ const fetchUser = (id) => {
284
+ return new Promise((resolve, reject) => {
285
+ setTimeout(() => {
286
+ if (id > 0) {
287
+ resolve({ id, name: "John" });
288
+ } else {
289
+ reject(new Error("Invalid ID"));
290
+ }
291
+ }, 1000);
292
+ });
293
+ };
294
+
295
+ // Using promises
296
+ fetchUser(1)
297
+ .then((user) => console.log(user))
298
+ .catch((error) => console.error(error))
299
+ .finally(() => console.log("Done"));
300
+
301
+ // Chaining promises
302
+ fetchUser(1)
303
+ .then((user) => fetchUserPosts(user.id))
304
+ .then((posts) => processPosts(posts))
305
+ .then((result) => console.log(result))
306
+ .catch((error) => console.error(error));
307
+ ```
308
+
309
+ **Promise Combinators:**
310
+
311
+ ```javascript
312
+ // Promise.all - Wait for all promises
313
+ const promises = [fetchUser(1), fetchUser(2), fetchUser(3)];
314
+
315
+ Promise.all(promises)
316
+ .then((users) => console.log(users))
317
+ .catch((error) => console.error("At least one failed:", error));
318
+
319
+ // Promise.allSettled - Wait for all, regardless of outcome
320
+ Promise.allSettled(promises).then((results) => {
321
+ results.forEach((result) => {
322
+ if (result.status === "fulfilled") {
323
+ console.log("Success:", result.value);
324
+ } else {
325
+ console.log("Error:", result.reason);
326
+ }
327
+ });
328
+ });
329
+
330
+ // Promise.race - First to complete
331
+ Promise.race(promises)
332
+ .then((winner) => console.log("First:", winner))
333
+ .catch((error) => console.error(error));
334
+
335
+ // Promise.any - First to succeed
336
+ Promise.any(promises)
337
+ .then((first) => console.log("First success:", first))
338
+ .catch((error) => console.error("All failed:", error));
339
+ ```
340
+
341
+ ### 2. Async/Await
342
+
343
+ **Basic Usage:**
344
+
345
+ ```javascript
346
+ // Async function always returns a Promise
347
+ async function fetchUser(id) {
348
+ const response = await fetch(`/api/users/${id}`);
349
+ const user = await response.json();
350
+ return user;
351
+ }
352
+
353
+ // Error handling with try/catch
354
+ async function getUserData(id) {
355
+ try {
356
+ const user = await fetchUser(id);
357
+ const posts = await fetchUserPosts(user.id);
358
+ return { user, posts };
359
+ } catch (error) {
360
+ console.error("Error fetching data:", error);
361
+ throw error;
362
+ }
363
+ }
364
+
365
+ // Sequential vs Parallel execution
366
+ async function sequential() {
367
+ const user1 = await fetchUser(1); // Wait
368
+ const user2 = await fetchUser(2); // Then wait
369
+ return [user1, user2];
370
+ }
371
+
372
+ async function parallel() {
373
+ const [user1, user2] = await Promise.all([fetchUser(1), fetchUser(2)]);
374
+ return [user1, user2];
375
+ }
376
+ ```
377
+
378
+ **Advanced Patterns:**
379
+
380
+ ```javascript
381
+ // Async IIFE
382
+ (async () => {
383
+ const result = await someAsyncOperation();
384
+ console.log(result);
385
+ })();
386
+
387
+ // Async iteration
388
+ async function processUsers(userIds) {
389
+ for (const id of userIds) {
390
+ const user = await fetchUser(id);
391
+ await processUser(user);
392
+ }
393
+ }
394
+
395
+ // Top-level await (ES2022)
396
+ const config = await fetch("/config.json").then((r) => r.json());
397
+
398
+ // Retry logic
399
+ async function fetchWithRetry(url, retries = 3) {
400
+ for (let i = 0; i < retries; i++) {
401
+ try {
402
+ return await fetch(url);
403
+ } catch (error) {
404
+ if (i === retries - 1) throw error;
405
+ await new Promise((resolve) => setTimeout(resolve, 1000 * (i + 1)));
406
+ }
407
+ }
408
+ }
409
+
410
+ // Timeout wrapper
411
+ async function withTimeout(promise, ms) {
412
+ const timeout = new Promise((_, reject) =>
413
+ setTimeout(() => reject(new Error("Timeout")), ms),
414
+ );
415
+ return Promise.race([promise, timeout]);
416
+ }
417
+ ```
418
+
419
+ ## Functional Programming Patterns
420
+
421
+ ### 1. Array Methods
422
+
423
+ **Map, Filter, Reduce:**
424
+
425
+ ```javascript
426
+ const users = [
427
+ { id: 1, name: "John", age: 30, active: true },
428
+ { id: 2, name: "Jane", age: 25, active: false },
429
+ { id: 3, name: "Bob", age: 35, active: true },
430
+ ];
431
+
432
+ // Map - Transform array
433
+ const names = users.map((user) => user.name);
434
+ const upperNames = users.map((user) => user.name.toUpperCase());
435
+
436
+ // Filter - Select elements
437
+ const activeUsers = users.filter((user) => user.active);
438
+ const adults = users.filter((user) => user.age >= 18);
439
+
440
+ // Reduce - Aggregate data
441
+ const totalAge = users.reduce((sum, user) => sum + user.age, 0);
442
+ const avgAge = totalAge / users.length;
443
+
444
+ // Group by property
445
+ const byActive = users.reduce((groups, user) => {
446
+ const key = user.active ? "active" : "inactive";
447
+ return {
448
+ ...groups,
449
+ [key]: [...(groups[key] || []), user],
450
+ };
451
+ }, {});
452
+
453
+ // Chaining methods
454
+ const result = users
455
+ .filter((user) => user.active)
456
+ .map((user) => user.name)
457
+ .sort()
458
+ .join(", ");
459
+ ```
460
+
461
+ **Advanced Array Methods:**
462
+
463
+ ```javascript
464
+ // Find - First matching element
465
+ const user = users.find((u) => u.id === 2);
466
+
467
+ // FindIndex - Index of first match
468
+ const index = users.findIndex((u) => u.name === "Jane");
469
+
470
+ // Some - At least one matches
471
+ const hasActive = users.some((u) => u.active);
472
+
473
+ // Every - All match
474
+ const allAdults = users.every((u) => u.age >= 18);
475
+
476
+ // FlatMap - Map and flatten
477
+ const userTags = [
478
+ { name: "John", tags: ["admin", "user"] },
479
+ { name: "Jane", tags: ["user"] },
480
+ ];
481
+ const allTags = userTags.flatMap((u) => u.tags);
482
+
483
+ // From - Create array from iterable
484
+ const str = "hello";
485
+ const chars = Array.from(str);
486
+ const numbers = Array.from({ length: 5 }, (_, i) => i + 1);
487
+
488
+ // Of - Create array from arguments
489
+ const arr = Array.of(1, 2, 3);
490
+ ```
491
+
492
+ ### 2. Higher-Order Functions
493
+
494
+ **Functions as Arguments:**
495
+
496
+ ```javascript
497
+ // Custom forEach
498
+ function forEach(array, callback) {
499
+ for (let i = 0; i < array.length; i++) {
500
+ callback(array[i], i, array);
501
+ }
502
+ }
503
+
504
+ // Custom map
505
+ function map(array, transform) {
506
+ const result = [];
507
+ for (const item of array) {
508
+ result.push(transform(item));
509
+ }
510
+ return result;
511
+ }
512
+
513
+ // Custom filter
514
+ function filter(array, predicate) {
515
+ const result = [];
516
+ for (const item of array) {
517
+ if (predicate(item)) {
518
+ result.push(item);
519
+ }
520
+ }
521
+ return result;
522
+ }
523
+ ```
524
+
525
+ **Functions Returning Functions:**
526
+
527
+ ```javascript
528
+ // Currying
529
+ const multiply = (a) => (b) => a * b;
530
+ const double = multiply(2);
531
+ const triple = multiply(3);
532
+
533
+ console.log(double(5)); // 10
534
+ console.log(triple(5)); // 15
535
+
536
+ // Partial application
537
+ function partial(fn, ...args) {
538
+ return (...moreArgs) => fn(...args, ...moreArgs);
539
+ }
540
+
541
+ const add = (a, b, c) => a + b + c;
542
+ const add5 = partial(add, 5);
543
+ console.log(add5(3, 2)); // 10
544
+
545
+ // Memoization
546
+ function memoize(fn) {
547
+ const cache = new Map();
548
+ return (...args) => {
549
+ const key = JSON.stringify(args);
550
+ if (cache.has(key)) {
551
+ return cache.get(key);
552
+ }
553
+ const result = fn(...args);
554
+ cache.set(key, result);
555
+ return result;
556
+ };
557
+ }
558
+
559
+ const fibonacci = memoize((n) => {
560
+ if (n <= 1) return n;
561
+ return fibonacci(n - 1) + fibonacci(n - 2);
562
+ });
563
+ ```
564
+
565
+ ### 3. Composition and Piping
566
+
567
+ ```javascript
568
+ // Function composition
569
+ const compose =
570
+ (...fns) =>
571
+ (x) =>
572
+ fns.reduceRight((acc, fn) => fn(acc), x);
573
+
574
+ const pipe =
575
+ (...fns) =>
576
+ (x) =>
577
+ fns.reduce((acc, fn) => fn(acc), x);
578
+
579
+ // Example usage
580
+ const addOne = (x) => x + 1;
581
+ const double = (x) => x * 2;
582
+ const square = (x) => x * x;
583
+
584
+ const composed = compose(square, double, addOne);
585
+ console.log(composed(3)); // ((3 + 1) * 2)^2 = 64
586
+
587
+ const piped = pipe(addOne, double, square);
588
+ console.log(piped(3)); // ((3 + 1) * 2)^2 = 64
589
+
590
+ // Practical example
591
+ const processUser = pipe(
592
+ (user) => ({ ...user, name: user.name.trim() }),
593
+ (user) => ({ ...user, email: user.email.toLowerCase() }),
594
+ (user) => ({ ...user, age: parseInt(user.age) }),
595
+ );
596
+
597
+ const user = processUser({
598
+ name: " John ",
599
+ email: "JOHN@EXAMPLE.COM",
600
+ age: "30",
601
+ });
602
+ ```
603
+
604
+ ### 4. Pure Functions and Immutability
605
+
606
+ ```javascript
607
+ // Impure function (modifies input)
608
+ function addItemImpure(cart, item) {
609
+ cart.items.push(item);
610
+ cart.total += item.price;
611
+ return cart;
612
+ }
613
+
614
+ // Pure function (no side effects)
615
+ function addItemPure(cart, item) {
616
+ return {
617
+ ...cart,
618
+ items: [...cart.items, item],
619
+ total: cart.total + item.price,
620
+ };
621
+ }
622
+
623
+ // Immutable array operations
624
+ const numbers = [1, 2, 3, 4, 5];
625
+
626
+ // Add to array
627
+ const withSix = [...numbers, 6];
628
+
629
+ // Remove from array
630
+ const withoutThree = numbers.filter((n) => n !== 3);
631
+
632
+ // Update array element
633
+ const doubled = numbers.map((n) => (n === 3 ? n * 2 : n));
634
+
635
+ // Immutable object operations
636
+ const user = { name: "John", age: 30 };
637
+
638
+ // Update property
639
+ const olderUser = { ...user, age: 31 };
640
+
641
+ // Add property
642
+ const withEmail = { ...user, email: "john@example.com" };
643
+
644
+ // Remove property
645
+ const { age, ...withoutAge } = user;
646
+
647
+ // Deep cloning (simple approach)
648
+ const deepClone = (obj) => JSON.parse(JSON.stringify(obj));
649
+
650
+ // Better deep cloning
651
+ const structuredClone = (obj) => globalThis.structuredClone(obj);
652
+ ```
653
+
654
+ ## Modern Class Features
655
+
656
+ ```javascript
657
+ // Class syntax
658
+ class User {
659
+ // Private fields
660
+ #password;
661
+
662
+ // Public fields
663
+ id;
664
+ name;
665
+
666
+ // Static field
667
+ static count = 0;
668
+
669
+ constructor(id, name, password) {
670
+ this.id = id;
671
+ this.name = name;
672
+ this.#password = password;
673
+ User.count++;
674
+ }
675
+
676
+ // Public method
677
+ greet() {
678
+ return `Hello, ${this.name}`;
679
+ }
680
+
681
+ // Private method
682
+ #hashPassword(password) {
683
+ return `hashed_${password}`;
684
+ }
685
+
686
+ // Getter
687
+ get displayName() {
688
+ return this.name.toUpperCase();
689
+ }
690
+
691
+ // Setter
692
+ set password(newPassword) {
693
+ this.#password = this.#hashPassword(newPassword);
694
+ }
695
+
696
+ // Static method
697
+ static create(id, name, password) {
698
+ return new User(id, name, password);
699
+ }
700
+ }
701
+
702
+ // Inheritance
703
+ class Admin extends User {
704
+ constructor(id, name, password, role) {
705
+ super(id, name, password);
706
+ this.role = role;
707
+ }
708
+
709
+ greet() {
710
+ return `${super.greet()}, I'm an admin`;
711
+ }
712
+ }
713
+ ```
714
+
715
+ ## Modules (ES6)
716
+
717
+ ```javascript
718
+ // Exporting
719
+ // math.js
720
+ export const PI = 3.14159;
721
+ export function add(a, b) {
722
+ return a + b;
723
+ }
724
+ export class Calculator {
725
+ // ...
726
+ }
727
+
728
+ // Default export
729
+ export default function multiply(a, b) {
730
+ return a * b;
731
+ }
732
+
733
+ // Importing
734
+ // app.js
735
+ import multiply, { PI, add, Calculator } from "./math.js";
736
+
737
+ // Rename imports
738
+ import { add as sum } from "./math.js";
739
+
740
+ // Import all
741
+ import * as Math from "./math.js";
742
+
743
+ // Dynamic imports
744
+ const module = await import("./math.js");
745
+ const { add } = await import("./math.js");
746
+
747
+ // Conditional loading
748
+ if (condition) {
749
+ const module = await import("./feature.js");
750
+ module.init();
751
+ }
752
+ ```
753
+
754
+ ## Iterators and Generators
755
+
756
+ ```javascript
757
+ // Custom iterator
758
+ const range = {
759
+ from: 1,
760
+ to: 5,
761
+
762
+ [Symbol.iterator]() {
763
+ return {
764
+ current: this.from,
765
+ last: this.to,
766
+
767
+ next() {
768
+ if (this.current <= this.last) {
769
+ return { done: false, value: this.current++ };
770
+ } else {
771
+ return { done: true };
772
+ }
773
+ },
774
+ };
775
+ },
776
+ };
777
+
778
+ for (const num of range) {
779
+ console.log(num); // 1, 2, 3, 4, 5
780
+ }
781
+
782
+ // Generator function
783
+ function* rangeGenerator(from, to) {
784
+ for (let i = from; i <= to; i++) {
785
+ yield i;
786
+ }
787
+ }
788
+
789
+ for (const num of rangeGenerator(1, 5)) {
790
+ console.log(num);
791
+ }
792
+
793
+ // Infinite generator
794
+ function* fibonacci() {
795
+ let [prev, curr] = [0, 1];
796
+ while (true) {
797
+ yield curr;
798
+ [prev, curr] = [curr, prev + curr];
799
+ }
800
+ }
801
+
802
+ // Async generator
803
+ async function* fetchPages(url) {
804
+ let page = 1;
805
+ while (true) {
806
+ const response = await fetch(`${url}?page=${page}`);
807
+ const data = await response.json();
808
+ if (data.length === 0) break;
809
+ yield data;
810
+ page++;
811
+ }
812
+ }
813
+
814
+ for await (const page of fetchPages("/api/users")) {
815
+ console.log(page);
816
+ }
817
+ ```
818
+
819
+ ## Modern Operators
820
+
821
+ ```javascript
822
+ // Optional chaining
823
+ const user = { name: "John", address: { city: "NYC" } };
824
+ const city = user?.address?.city;
825
+ const zipCode = user?.address?.zipCode; // undefined
826
+
827
+ // Function call
828
+ const result = obj.method?.();
829
+
830
+ // Array access
831
+ const first = arr?.[0];
832
+
833
+ // Nullish coalescing
834
+ const value = null ?? "default"; // 'default'
835
+ const value = undefined ?? "default"; // 'default'
836
+ const value = 0 ?? "default"; // 0 (not 'default')
837
+ const value = "" ?? "default"; // '' (not 'default')
838
+
839
+ // Logical assignment
840
+ let a = null;
841
+ a ??= "default"; // a = 'default'
842
+
843
+ let b = 5;
844
+ b ??= 10; // b = 5 (unchanged)
845
+
846
+ let obj = { count: 0 };
847
+ obj.count ||= 1; // obj.count = 1
848
+ obj.count &&= 2; // obj.count = 2
849
+ ```
850
+
851
+ ## Performance Optimization
852
+
853
+ ```javascript
854
+ // Debounce
855
+ function debounce(fn, delay) {
856
+ let timeoutId;
857
+ return (...args) => {
858
+ clearTimeout(timeoutId);
859
+ timeoutId = setTimeout(() => fn(...args), delay);
860
+ };
861
+ }
862
+
863
+ const searchDebounced = debounce(search, 300);
864
+
865
+ // Throttle
866
+ function throttle(fn, limit) {
867
+ let inThrottle;
868
+ return (...args) => {
869
+ if (!inThrottle) {
870
+ fn(...args);
871
+ inThrottle = true;
872
+ setTimeout(() => (inThrottle = false), limit);
873
+ }
874
+ };
875
+ }
876
+
877
+ const scrollThrottled = throttle(handleScroll, 100);
878
+
879
+ // Lazy evaluation
880
+ function* lazyMap(iterable, transform) {
881
+ for (const item of iterable) {
882
+ yield transform(item);
883
+ }
884
+ }
885
+
886
+ // Use only what you need
887
+ const numbers = [1, 2, 3, 4, 5];
888
+ const doubled = lazyMap(numbers, (x) => x * 2);
889
+ const first = doubled.next().value; // Only computes first value
890
+ ```
891
+
892
+ ## Best Practices
893
+
894
+ 1. **Use const by default**: Only use let when reassignment is needed
895
+ 2. **Prefer arrow functions**: Especially for callbacks
896
+ 3. **Use template literals**: Instead of string concatenation
897
+ 4. **Destructure objects and arrays**: For cleaner code
898
+ 5. **Use async/await**: Instead of Promise chains
899
+ 6. **Avoid mutating data**: Use spread operator and array methods
900
+ 7. **Use optional chaining**: Prevent "Cannot read property of undefined"
901
+ 8. **Use nullish coalescing**: For default values
902
+ 9. **Prefer array methods**: Over traditional loops
903
+ 10. **Use modules**: For better code organization
904
+ 11. **Write pure functions**: Easier to test and reason about
905
+ 12. **Use meaningful variable names**: Self-documenting code
906
+ 13. **Keep functions small**: Single responsibility principle
907
+ 14. **Handle errors properly**: Use try/catch with async/await
908
+ 15. **Use strict mode**: `'use strict'` for better error catching
909
+
910
+ ## Common Pitfalls
911
+
912
+ 1. **this binding confusion**: Use arrow functions or bind()
913
+ 2. **Async/await without error handling**: Always use try/catch
914
+ 3. **Promise creation unnecessary**: Don't wrap already async functions
915
+ 4. **Mutation of objects**: Use spread operator or Object.assign()
916
+ 5. **Forgetting await**: Async functions return promises
917
+ 6. **Blocking event loop**: Avoid synchronous operations
918
+ 7. **Memory leaks**: Clean up event listeners and timers
919
+ 8. **Not handling promise rejections**: Use catch() or try/catch
920
+
921
+ ## Resources
922
+
923
+ - **MDN Web Docs**: https://developer.mozilla.org/en-US/docs/Web/JavaScript
924
+ - **JavaScript.info**: https://javascript.info/
925
+ - **You Don't Know JS**: https://github.com/getify/You-Dont-Know-JS
926
+ - **Eloquent JavaScript**: https://eloquentjavascript.net/
927
+ - **ES6 Features**: http://es6-features.org/