-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathincludes-indexOf.js
More file actions
468 lines (357 loc) · 15.2 KB
/
includes-indexOf.js
File metadata and controls
468 lines (357 loc) · 15.2 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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
/**
* Array Search Methods: includes(), indexOf(), lastIndexOf()
*
* Description:
* - includes(): Determines whether an array includes a certain value (ES2016)
* - indexOf(): Returns the first index at which a given element can be found
* - lastIndexOf(): Returns the last index at which a given element can be found
*
* Syntax:
* - array.includes(searchElement, fromIndex)
* - array.indexOf(searchElement, fromIndex)
* - array.lastIndexOf(searchElement, fromIndex)
*
* Returns:
* - includes(): boolean (true/false)
* - indexOf(): number (index or -1 if not found)
* - lastIndexOf(): number (last index or -1 if not found)
*
* Time Complexity: O(n)
* Space Complexity: O(1)
*/
// ========================================
// ARRAY.PROTOTYPE.INCLUDES() EXAMPLES
// ========================================
console.log("=== Array.includes() Examples ===\n");
// Example 1: Basic includes() usage
console.log("Example 1: Basic includes()");
const numbers = [1, 2, 3, 4, 5];
console.log("Array:", numbers);
console.log("includes(3):", numbers.includes(3)); // true
console.log("includes(6):", numbers.includes(6)); // false
console.log("includes(1):", numbers.includes(1)); // true
console.log();
// Example 2: includes() with fromIndex
console.log("Example 2: includes() with fromIndex");
const fruits = ["apple", "banana", "cherry", "banana", "date"];
console.log("Fruits:", fruits);
console.log("includes('banana'):", fruits.includes("banana")); // true
console.log("includes('banana', 2):", fruits.includes("banana", 2)); // true (finds second banana)
console.log("includes('banana', 4):", fruits.includes("banana", 4)); // false
console.log("includes('apple', 1):", fruits.includes("apple", 1)); // false
console.log();
// Example 3: includes() with negative index
console.log("Example 3: includes() with negative index");
console.log("includes('date', -2):", fruits.includes("date", -2)); // true (searches last 2 elements)
console.log("includes('cherry', -1):", fruits.includes("cherry", -1)); // false
console.log();
// Example 4: includes() with NaN
console.log("Example 4: includes() handles NaN correctly");
const withNaN = [1, 2, NaN, 4];
console.log("Array:", withNaN);
console.log("includes(NaN):", withNaN.includes(NaN)); // true ✓
console.log("indexOf(NaN):", withNaN.indexOf(NaN)); // -1 (indexOf can't find NaN)
console.log("Note: includes() can find NaN, indexOf() cannot");
console.log();
// ========================================
// ARRAY.PROTOTYPE.INDEXOF() EXAMPLES
// ========================================
console.log("=== Array.indexOf() Examples ===\n");
// Example 5: Basic indexOf() usage
console.log("Example 5: Basic indexOf()");
const animals = ["cat", "dog", "rabbit", "dog", "fish"];
console.log("Animals:", animals);
console.log("indexOf('dog'):", animals.indexOf("dog")); // 1 (first occurrence)
console.log("indexOf('rabbit'):", animals.indexOf("rabbit")); // 2
console.log("indexOf('bird'):", animals.indexOf("bird")); // -1 (not found)
console.log();
// Example 6: indexOf() with fromIndex
console.log("Example 6: indexOf() with fromIndex");
console.log("indexOf('dog', 0):", animals.indexOf("dog", 0)); // 1
console.log("indexOf('dog', 2):", animals.indexOf("dog", 2)); // 3 (second occurrence)
console.log("indexOf('dog', 4):", animals.indexOf("dog", 4)); // -1
console.log();
// Example 7: indexOf() with negative index
console.log("Example 7: indexOf() with negative index");
const letters = ["a", "b", "c", "d", "e"];
console.log("Letters:", letters);
console.log("indexOf('d', -3):", letters.indexOf("d", -3)); // 3 (searches from index 2)
console.log("indexOf('b', -4):", letters.indexOf("b", -4)); // 1
console.log();
// ========================================
// ARRAY.PROTOTYPE.LASTINDEXOF() EXAMPLES
// ========================================
console.log("=== Array.lastIndexOf() Examples ===\n");
// Example 8: Basic lastIndexOf() usage
console.log("Example 8: Basic lastIndexOf()");
const repeatedNumbers = [1, 2, 3, 2, 1, 4, 2];
console.log("Array:", repeatedNumbers);
console.log("lastIndexOf(2):", repeatedNumbers.lastIndexOf(2)); // 6 (last occurrence)
console.log("lastIndexOf(1):", repeatedNumbers.lastIndexOf(1)); // 4
console.log("lastIndexOf(5):", repeatedNumbers.lastIndexOf(5)); // -1
console.log();
// Example 9: lastIndexOf() with fromIndex
console.log("Example 9: lastIndexOf() with fromIndex");
console.log("lastIndexOf(2, 5):", repeatedNumbers.lastIndexOf(2, 5)); // 3
console.log("lastIndexOf(2, 2):", repeatedNumbers.lastIndexOf(2, 2)); // 1
console.log("lastIndexOf(1, 3):", repeatedNumbers.lastIndexOf(1, 3)); // 0
console.log("Note: fromIndex searches backwards from that position");
console.log();
// ========================================
// COMPARISON OF METHODS
// ========================================
console.log("=== Comparison of Search Methods ===\n");
const testArray = [10, 20, 30, 20, 40, 20, 50];
console.log("Test array:", testArray);
console.log("\nSearching for 20:");
console.log("includes(20):", testArray.includes(20)); // true
console.log("indexOf(20):", testArray.indexOf(20)); // 1 (first occurrence)
console.log("lastIndexOf(20):", testArray.lastIndexOf(20)); // 5 (last occurrence)
console.log("\nSearching for 60:");
console.log("includes(60):", testArray.includes(60)); // false
console.log("indexOf(60):", testArray.indexOf(60)); // -1
console.log("lastIndexOf(60):", testArray.lastIndexOf(60)); // -1
console.log();
// ========================================
// STRICT EQUALITY (===)
// ========================================
console.log("=== Strict Equality Comparison ===\n");
// Example 10: Type matters
console.log("Example 10: Type-sensitive search");
const mixedTypes = [1, "1", 2, "2", 3];
console.log("Array:", mixedTypes);
console.log("includes(1):", mixedTypes.includes(1)); // true (number)
console.log("includes('1'):", mixedTypes.includes("1")); // true (string)
console.log("indexOf(1):", mixedTypes.indexOf(1)); // 0 (number at index 0)
console.log("indexOf('1'):", mixedTypes.indexOf("1")); // 1 (string at index 1)
console.log();
// Example 11: Object references
console.log("Example 11: Object reference comparison");
const obj1 = { id: 1 };
const obj2 = { id: 1 };
const objects = [obj1, { id: 2 }, { id: 3 }];
console.log("includes(obj1):", objects.includes(obj1)); // true (same reference)
console.log("includes(obj2):", objects.includes(obj2)); // false (different reference)
console.log("includes({id: 1}):", objects.includes({ id: 1 })); // false (new object)
console.log();
// ========================================
// PRACTICAL USE CASES
// ========================================
// Use Case 1: Checking user permissions
console.log("Use Case 1: Permission checking");
const userPermissions = ["read", "write", "execute"];
const requiredPermissions = ["read", "write", "delete"];
function hasPermission(permission) {
return userPermissions.includes(permission);
}
function hasAllPermissions(required) {
return required.every(perm => userPermissions.includes(perm));
}
console.log("Has 'read' permission:", hasPermission("read"));
console.log("Has 'delete' permission:", hasPermission("delete"));
console.log("Has all required permissions:", hasAllPermissions(requiredPermissions));
console.log();
// Use Case 2: Filtering unique values
console.log("Use Case 2: Finding duplicates");
const allNumbers = [1, 2, 3, 2, 4, 1, 5, 3];
function findDuplicates(array) {
const duplicates = [];
array.forEach((item, index) => {
const firstIndex = array.indexOf(item);
if (firstIndex !== index && !duplicates.includes(item)) {
duplicates.push(item);
}
});
return duplicates;
}
function findUniqueValues(array) {
return array.filter((item, index) => array.indexOf(item) === index);
}
console.log("Array:", allNumbers);
console.log("Duplicates:", findDuplicates(allNumbers));
console.log("Unique values:", findUniqueValues(allNumbers));
console.log();
// Use Case 3: Tag/Category filtering
console.log("Use Case 3: Tag filtering");
const articles = [
{ title: "Article 1", tags: ["javascript", "web", "tutorial"] },
{ title: "Article 2", tags: ["python", "data", "tutorial"] },
{ title: "Article 3", tags: ["javascript", "react", "web"] }
];
function filterByTag(tag) {
return articles.filter(article => article.tags.includes(tag));
}
function filterByTags(tags) {
return articles.filter(article =>
tags.every(tag => article.tags.includes(tag))
);
}
console.log("Articles with 'javascript' tag:");
console.log(filterByTag("javascript"));
console.log("\nArticles with both 'javascript' and 'web' tags:");
console.log(filterByTags(["javascript", "web"]));
console.log();
// Use Case 4: Form validation
console.log("Use Case 4: Allowed values validation");
const allowedCountries = ["US", "UK", "CA", "AU", "NZ"];
const allowedAgeRanges = ["18-25", "26-35", "36-45", "46-55", "56+"];
function validateFormData(data) {
const errors = [];
if (!allowedCountries.includes(data.country)) {
errors.push(`Invalid country: ${data.country}`);
}
if (!allowedAgeRanges.includes(data.ageRange)) {
errors.push(`Invalid age range: ${data.ageRange}`);
}
return {
isValid: errors.length === 0,
errors
};
}
console.log("Validation test 1:", validateFormData({ country: "US", ageRange: "26-35" }));
console.log("Validation test 2:", validateFormData({ country: "FR", ageRange: "100+" }));
console.log();
// ========================================
// ADVANCED PATTERNS
// ========================================
// Example 12: Finding all occurrences
console.log("Example 12: Finding all occurrences");
function findAllIndexes(array, value) {
const indexes = [];
let index = array.indexOf(value);
while (index !== -1) {
indexes.push(index);
index = array.indexOf(value, index + 1);
}
return indexes;
}
const values = [1, 2, 3, 2, 4, 2, 5];
console.log("Array:", values);
console.log("All indexes of 2:", findAllIndexes(values, 2));
console.log();
// Example 13: Case-insensitive search
console.log("Example 13: Case-insensitive includes");
function includesIgnoreCase(array, searchValue) {
return array.some(item =>
String(item).toLowerCase() === String(searchValue).toLowerCase()
);
}
const tags = ["JavaScript", "Python", "JAVA", "ruby"];
console.log("Tags:", tags);
console.log("includesIgnoreCase('javascript'):", includesIgnoreCase(tags, "javascript"));
console.log("includesIgnoreCase('RUBY'):", includesIgnoreCase(tags, "RUBY"));
console.log();
// ========================================
// EDGE CASES
// ========================================
console.log("=== Edge Cases ===\n");
// Example 14: Empty arrays
console.log("Example 14: Empty arrays");
const empty = [];
console.log("Empty array includes(1):", empty.includes(1)); // false
console.log("Empty array indexOf(1):", empty.indexOf(1)); // -1
console.log();
// Example 15: Sparse arrays
console.log("Example 15: Sparse arrays");
const sparse = [1, , 3, , 5];
console.log("Sparse array:", sparse);
console.log("includes(undefined):", sparse.includes(undefined)); // true (holes are undefined)
console.log("indexOf(undefined):", sparse.indexOf(undefined)); // -1 (doesn't find holes)
console.log();
// Example 16: Special values
console.log("Example 16: Special values");
const special = [0, -0, null, undefined, false, ""];
console.log("includes(0):", special.includes(0)); // true
console.log("includes(-0):", special.includes(-0)); // true (0 === -0)
console.log("includes(null):", special.includes(null)); // true
console.log("includes(undefined):", special.includes(undefined)); // true
console.log("includes(false):", special.includes(false)); // true
console.log("includes(''):", special.includes("")); // true
console.log();
// ========================================
// PERFORMANCE CONSIDERATIONS
// ========================================
console.log("=== Performance Considerations ===\n");
const largeArray = Array.from({ length: 100000 }, (_, i) => i);
// Search at beginning
console.time("indexOf (at start)");
largeArray.indexOf(5);
console.timeEnd("indexOf (at start)");
// Search at end
console.time("indexOf (at end)");
largeArray.indexOf(99995);
console.timeEnd("indexOf (at end)");
// Not found (worst case)
console.time("indexOf (not found)");
largeArray.indexOf(999999);
console.timeEnd("indexOf (not found)");
console.log("Note: For large arrays and repeated searches, consider using Set");
// Using Set for better performance
console.time("Set.has() performance");
const numberSet = new Set(largeArray);
numberSet.has(99995);
console.timeEnd("Set.has() performance");
console.log();
// ========================================
// CUSTOM IMPLEMENTATIONS
// ========================================
// Custom includes implementation
Array.prototype.customIncludes = function(searchElement, fromIndex = 0) {
const O = Object(this);
const len = parseInt(O.length) || 0;
if (len === 0) return false;
let k = Math.max(fromIndex >= 0 ? fromIndex : len + fromIndex, 0);
while (k < len) {
const elementK = O[k];
// SameValueZero comparison (can find NaN)
if (searchElement === elementK || (Number.isNaN(searchElement) && Number.isNaN(elementK))) {
return true;
}
k++;
}
return false;
};
// Test custom implementation
console.log("Custom implementation test:");
const testArr = [1, 2, NaN, 4];
console.log("Array:", testArr);
console.log("customIncludes(NaN):", testArr.customIncludes(NaN));
console.log("customIncludes(2, 2):", testArr.customIncludes(2, 2));
console.log();
// ========================================
// BEST PRACTICES
// ========================================
console.log("=== Best Practices ===");
console.log("1. Use includes() for simple existence checks (cleaner, returns boolean)");
console.log("2. Use indexOf() when you need the position of an element");
console.log("3. Use lastIndexOf() to find the last occurrence");
console.log("4. includes() can find NaN, indexOf() cannot");
console.log("5. All three use strict equality (===) for comparison");
console.log("6. Remember: indexOf() returns -1 if not found, includes() returns false");
console.log("7. For large arrays with repeated searches, use Set instead");
console.log("8. Use find() for complex object searches");
console.log("9. Negative fromIndex counts from the end");
console.log("10. For case-insensitive search, convert to lowercase first");
console.log("\n=== Common Patterns ===");
// Pattern 1: Existence check (modern)
const hasElement = (arr, element) => arr.includes(element);
// Pattern 2: Multiple checks
const hasAny = (arr, values) => values.some(val => arr.includes(val));
const hasAll = (arr, values) => values.every(val => arr.includes(val));
// Pattern 3: Safe index check
const getElementByValue = (arr, value) => {
const index = arr.indexOf(value);
return index !== -1 ? arr[index] : null;
};
// Pattern 4: Toggle element (add/remove)
function toggleElement(arr, element) {
const index = arr.indexOf(element);
if (index === -1) {
arr.push(element);
} else {
arr.splice(index, 1);
}
return arr;
}
console.log("\nToggle example:", toggleElement([1, 2, 3], 2)); // removes 2
console.log("Toggle example:", toggleElement([1, 3], 2)); // adds 2