-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmap.js
More file actions
255 lines (207 loc) · 7.77 KB
/
map.js
File metadata and controls
255 lines (207 loc) · 7.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
/**
* Array.prototype.map() Method
*
* Description:
* The map() method creates a new array populated with the results of calling
* a provided function on every element in the calling array.
*
* Syntax: array.map(callback(currentValue, index, array), thisArg)
*
* Parameters:
* - callback: Function that is called for every element
* - currentValue: The current element being processed
* - index (optional): The index of the current element
* - array (optional): The array map was called upon
* - thisArg (optional): Value to use as 'this' when executing callback
*
* Returns: A new array with each element being the result of the callback function
*
* Time Complexity: O(n)
* Space Complexity: O(n)
*/
// ========================================
// BASIC EXAMPLES
// ========================================
console.log("=== Array.map() Examples ===\n");
// Example 1: Transform numbers by doubling them
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(num => num * 2);
console.log("Example 1: Double numbers");
console.log("Input:", numbers);
console.log("Output:", doubled);
console.log("Original array unchanged:", numbers);
console.log();
// Example 2: Extract property from objects
const users = [
{ id: 1, name: "John", age: 25 },
{ id: 2, name: "Jane", age: 30 },
{ id: 3, name: "Bob", age: 35 }
];
const userNames = users.map(user => user.name);
const userAges = users.map(user => user.age);
console.log("Example 2: Extract properties from objects");
console.log("Users:", users);
console.log("Names:", userNames);
console.log("Ages:", userAges);
console.log();
// Example 3: Transform strings
const words = ["hello", "world", "javascript", "programming"];
const capitalizedWords = words.map(word => word.toUpperCase());
const wordLengths = words.map(word => word.length);
console.log("Example 3: Transform strings");
console.log("Original words:", words);
console.log("Capitalized:", capitalizedWords);
console.log("Word lengths:", wordLengths);
console.log();
// ========================================
// ADVANCED EXAMPLES
// ========================================
// Example 4: Using index parameter
const items = ["apple", "banana", "cherry"];
const indexedItems = items.map((item, index) => `${index}: ${item}`);
console.log("Example 4: Using index parameter");
console.log("Input:", items);
console.log("Output:", indexedItems);
console.log();
// Example 5: Complex transformation
const products = [
{ name: "Laptop", price: 999.99, category: "Electronics" },
{ name: "Book", price: 19.99, category: "Education" },
{ name: "Phone", price: 599.99, category: "Electronics" }
];
const productSummary = products.map(product => ({
name: product.name,
priceCategory: product.price > 500 ? "Expensive" : "Affordable",
formattedPrice: `$${product.price.toFixed(2)}`
}));
console.log("Example 5: Complex transformation");
console.log("Original products:", products);
console.log("Product summary:", productSummary);
console.log();
// Example 6: Chaining with other array methods
const scores = [85, 92, 78, 96, 88];
const processedScores = scores
.map(score => score + 5) // Add bonus points
.filter(score => score >= 90) // Keep only high scores
.map(score => `Grade: ${score >= 95 ? 'A+' : 'A'}`); // Convert to grades
console.log("Example 6: Chaining with other methods");
console.log("Original scores:", scores);
console.log("Processed scores:", processedScores);
console.log();
// ========================================
// CUSTOM IMPLEMENTATION
// ========================================
// Custom implementation of map method
Array.prototype.customMap = function(callback, thisArg) {
// Handle edge cases
if (this == null) {
throw new TypeError('Array.prototype.customMap called on null or undefined');
}
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
}
const O = Object(this);
const len = parseInt(O.length) || 0;
const result = new Array(len);
for (let i = 0; i < len; i++) {
if (i in O) {
result[i] = callback.call(thisArg, O[i], i, O);
}
}
return result;
};
// Test custom implementation
const testArray = [1, 2, 3, 4];
const customResult = testArray.customMap(x => x * 3);
console.log("Example 7: Custom implementation");
console.log("Input:", testArray);
console.log("Custom map result:", customResult);
console.log();
// ========================================
// PRACTICAL USE CASES
// ========================================
// Use Case 1: API data transformation
const apiResponse = [
{ user_id: 1, first_name: "John", last_name: "Doe", email: "john@example.com" },
{ user_id: 2, first_name: "Jane", last_name: "Smith", email: "jane@example.com" }
];
const frontendUsers = apiResponse.map(user => ({
id: user.user_id,
fullName: `${user.first_name} ${user.last_name}`,
email: user.email,
initials: `${user.first_name[0]}${user.last_name[0]}`
}));
console.log("Use Case 1: API data transformation");
console.log("API Response:", apiResponse);
console.log("Frontend Format:", frontendUsers);
console.log();
// Use Case 2: Mathematical operations
const temperatures = [32, 68, 86, 104]; // Fahrenheit
const celsiusTemperatures = temperatures.map(f => ((f - 32) * 5/9).toFixed(1));
console.log("Use Case 2: Temperature conversion");
console.log("Fahrenheit:", temperatures);
console.log("Celsius:", celsiusTemperatures);
console.log();
// Use Case 3: React-like component mapping
const menuItems = ["Home", "About", "Services", "Contact"];
const navElements = menuItems.map((item, index) => ({
id: index,
label: item,
href: `/${item.toLowerCase()}`,
isActive: index === 0
}));
console.log("Use Case 3: Navigation elements");
console.log("Menu items:", menuItems);
console.log("Nav elements:", navElements);
console.log();
// ========================================
// PERFORMANCE CONSIDERATIONS
// ========================================
console.log("=== Performance Comparison ===");
// Performance test
const largeArray = Array.from({ length: 100000 }, (_, i) => i);
console.time("map() performance");
const mappedLarge = largeArray.map(x => x * 2);
console.timeEnd("map() performance");
console.time("for loop performance");
const forLoopResult = [];
for (let i = 0; i < largeArray.length; i++) {
forLoopResult.push(largeArray[i] * 2);
}
console.timeEnd("for loop performance");
console.log();
// ========================================
// COMMON MISTAKES AND GOTCHAS
// ========================================
console.log("=== Common Mistakes ===");
// Mistake 1: Modifying original array
const originalArray = [{ value: 1 }, { value: 2 }];
const modifiedIncorrectly = originalArray.map(obj => {
obj.value *= 2; // This modifies the original!
return obj;
});
console.log("Mistake 1 - Original array modified:", originalArray);
// Correct way
const originalArray2 = [{ value: 1 }, { value: 2 }];
const modifiedCorrectly = originalArray2.map(obj => ({
...obj,
value: obj.value * 2
}));
console.log("Correct way - Original array unchanged:", originalArray2);
console.log("Modified correctly:", modifiedCorrectly);
console.log();
// Mistake 2: Not returning a value
const numbersWithUndefined = [1, 2, 3].map(num => {
if (num > 2) {
return num * 2;
}
// Missing return statement for other cases
});
console.log("Mistake 2 - Missing return:", numbersWithUndefined);
// Best practices summary
console.log("=== Best Practices ===");
console.log("1. Always return a value from the callback function");
console.log("2. Don't modify the original array elements");
console.log("3. Use map() for transformation, not for side effects");
console.log("4. Consider performance for very large arrays");
console.log("5. Chain with other array methods for complex operations");