@zimezone/z-command 1.0.1 → 1.1.1

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