Skip to content

Commit c828a96

Browse files
committed
fixed incorrect escaping in array-methods
1 parent f1532f2 commit c828a96

1 file changed

Lines changed: 76 additions & 76 deletions

File tree

  • src/sections/04-arrays-and-two-pointers/05-array-methods

src/sections/04-arrays-and-two-pointers/05-array-methods/index.md

Lines changed: 76 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,7 @@ Alex's musical career has evolved into a small business. They now need to analyz
233233

234234
"I need to analyze last month's performances," Alex tells their business partner, Jordan, while reviewing their performance logs.
235235

236-
\`\`\`javascript
236+
```javascript
237237
// Alex's performance data from last month
238238
const lastMonthPerformances = [
239239
{ venue: "The Blue Note", date: "2024-01-05", audience: 85, revenue: 450, songs: ["Thunderstruck", "Hotel California"] },
@@ -250,14 +250,14 @@ lastMonthPerformances.forEach((performance, index) => {
250250
const revenuePerPerson = (performance.revenue / performance.audience).toFixed(2);
251251
const songsPerformed = performance.songs.length;
252252

253-
console.log(\`Performance #\${index + 1}:\`);
254-
console.log(\` Venue: \${performance.venue}\`);
255-
console.log(\` Date: \${performance.date}\`);
256-
console.log(\` Audience: \${performance.audience} people\`);
257-
console.log(\` Revenue: $\${performance.revenue}\`);
258-
console.log(\` Revenue per person: $\${revenuePerPerson}\`);
259-
console.log(\` Songs performed: \${songsPerformed}\`);
260-
console.log(\` Song list: \${performance.songs.join(", ")}\`);
253+
console.log(`Performance #${index + 1}:`);
254+
console.log(` Venue: ${performance.venue}`);
255+
console.log(` Date: ${performance.date}`);
256+
console.log(` Audience: ${performance.audience} people`);
257+
console.log(` Revenue: $${performance.revenue}`);
258+
console.log(` Revenue per person: $${revenuePerPerson}`);
259+
console.log(` Songs performed: ${songsPerformed}`);
260+
console.log(` Song list: ${performance.songs.join(", ")}`);
261261
console.log("-".repeat(30));
262262
});
263263

@@ -268,48 +268,48 @@ const performanceAlerts = [];
268268
lastMonthPerformances.forEach(performance => {
269269
// Check for high-revenue performances
270270
if (performance.revenue > 500) {
271-
performanceAlerts.push(\`🎉 Excellent revenue at \${performance.venue}: $\${performance.revenue}\`);
271+
performanceAlerts.push(`🎉 Excellent revenue at ${performance.venue}: $${performance.revenue}`);
272272
totalNotifications++;
273273
}
274274

275275
// Check for large audiences
276276
if (performance.audience > 100) {
277-
performanceAlerts.push(\`👥 Large audience at \${performance.venue}: \${performance.audience} people\`);
277+
performanceAlerts.push(`👥 Large audience at ${performance.venue}: ${performance.audience} people`);
278278
totalNotifications++;
279279
}
280280
});
281281

282-
console.log("\\nPerformance Alerts:");
282+
console.log("\nPerformance Alerts:");
283283
performanceAlerts.forEach(alert => console.log(alert));
284-
console.log(\`\\nTotal alerts generated: \${totalNotifications}\`);
285-
\`\`\`
284+
console.log(`\nTotal alerts generated: ${totalNotifications}`);
285+
```
286286

287-
"The \`forEach()\` method is perfect when I need to do something with each performance but don't need to create a new array," Alex explains. "It's **O(n) time complexity** and is ideal for side effects like logging, updating databases, or generating reports."
287+
"The `forEach()` method is perfect when I need to do something with each performance but don't need to create a new array," Alex explains. "It's **O(n) time complexity** and is ideal for side effects like logging, updating databases, or generating reports."
288288

289289
### Calculating Business Metrics with reduce() - The Accumulator
290290

291291
Jordan looks at the performance data, "Can you calculate our total revenue and average audience size?"
292292

293-
"Absolutely! This is where \`reduce()\` shines," Alex says, pulling up their laptop.
293+
"Absolutely! This is where `reduce()` shines," Alex says, pulling up their laptop.
294294

295-
\`\`\`javascript
295+
```javascript
296296
// Calculate total revenue using reduce()
297297
const totalRevenue = lastMonthPerformances.reduce((accumulator, performance) => {
298298
return accumulator + performance.revenue;
299299
}, 0); // Start with 0
300300

301-
console.log(\`Total revenue last month: $\${totalRevenue}\`);
301+
console.log(`Total revenue last month: $${totalRevenue}`);
302302

303303
// Calculate total audience using reduce()
304304
const totalAudience = lastMonthPerformances.reduce((sum, performance) => {
305305
return sum + performance.audience;
306306
}, 0);
307307

308-
console.log(\`Total audience last month: \${totalAudience} people\`);
308+
console.log(`Total audience last month: ${totalAudience} people`);
309309

310310
// Calculate average audience size
311311
const averageAudience = (totalAudience / lastMonthPerformances.length).toFixed(1);
312-
console.log(\`Average audience size: \${averageAudience} people\`);
312+
console.log(`Average audience size: ${averageAudience} people`);
313313

314314
// More complex reduce - find the best performing venue
315315
const venueStats = lastMonthPerformances.reduce((stats, performance) => {
@@ -326,17 +326,17 @@ const venueStats = lastMonthPerformances.reduce((stats, performance) => {
326326
return stats;
327327
}, {});
328328

329-
console.log("\\nVenue Performance Statistics:");
329+
console.log("\nVenue Performance Statistics:");
330330
Object.keys(venueStats).forEach(venue => {
331331
const stats = venueStats[venue];
332332
const avgRevenue = (stats.totalRevenue / stats.performances).toFixed(2);
333333
const avgAudience = (stats.totalAudience / stats.performances).toFixed(1);
334334

335-
console.log(\`\${venue}:\`);
336-
console.log(\` Performances: \${stats.performances}\`);
337-
console.log(\` Total Revenue: $\${stats.totalRevenue}\`);
338-
console.log(\` Average Revenue: $\${avgRevenue}\`);
339-
console.log(\` Average Audience: \${avgAudience} people\`);
335+
console.log(`${venue}:`);
336+
console.log(` Performances: ${stats.performances}`);
337+
console.log(` Total Revenue: $${stats.totalRevenue}`);
338+
console.log(` Average Revenue: $${avgRevenue}`);
339+
console.log(` Average Audience: ${avgAudience} people`);
340340
});
341341

342342
// Find most popular songs using reduce
@@ -347,69 +347,69 @@ const songPopularity = lastMonthPerformances.reduce((popularity, performance) =>
347347
return popularity;
348348
}, {});
349349

350-
console.log("\\nSong Popularity (times performed):");
350+
console.log("\nSong Popularity (times performed):");
351351
Object.entries(songPopularity)
352352
.sort(([,a], [,b]) => b - a) // Sort by popularity
353353
.forEach(([song, count]) => {
354-
console.log(\` \${song}: \${count} times\`);
354+
console.log(` ${song}: ${count} times`);
355355
});
356-
\`\`\`
356+
```
357357

358-
"The \`reduce()\` method is like having a super-powered calculator," Alex explains enthusiastically. "It takes all my performance data and 'reduces' it down to a single value - whether that's a total, an average, or even a complex object with statistics. It's **O(n) time complexity** and incredibly versatile."
358+
"The `reduce()` method is like having a super-powered calculator," Alex explains enthusiastically. "It takes all my performance data and 'reduces' it down to a single value - whether that's a total, an average, or even a complex object with statistics. It's **O(n) time complexity** and incredibly versatile."
359359

360360
### Extracting Specific Data with slice() - The Precision Extractor
361361

362362
"I need to analyze just the last two performances for this week's planning," Alex mentions while preparing for a venue meeting.
363363

364-
\`\`\`javascript
364+
```javascript
365365
// Extract the last two performances using slice()
366366
const recentPerformances = lastMonthPerformances.slice(-2);
367367
console.log("Most recent performances:");
368368
recentPerformances.forEach(performance => {
369-
console.log(\`- \${performance.venue} on \${performance.date}: \${performance.audience} people, $\${performance.revenue}\`);
369+
console.log(`- ${performance.venue} on ${performance.date}: ${performance.audience} people, $${performance.revenue}`);
370370
});
371371

372372
// Extract the first half of the month's performances
373373
const firstHalf = lastMonthPerformances.slice(0, 2);
374-
console.log("\\nFirst half of month:");
374+
console.log("\nFirst half of month:");
375375
firstHalf.forEach(performance => {
376-
console.log(\`- \${performance.venue} on \${performance.date}\`);
376+
console.log(`- ${performance.venue} on ${performance.date}`);
377377
});
378378

379379
// Extract middle performances (excluding first and last)
380380
const middlePerformances = lastMonthPerformances.slice(1, -1);
381-
console.log("\\nMiddle performances:");
381+
console.log("\nMiddle performances:");
382382
middlePerformances.forEach(performance => {
383-
console.log(\`- \${performance.venue} on \${performance.date}\`);
383+
console.log(`- ${performance.venue} on ${performance.date}`);
384384
});
385385

386386
// Create a copy of all performances for backup
387387
const performanceBackup = lastMonthPerformances.slice();
388-
console.log(\`\\nCreated backup of \${performanceBackup.length} performances\`);
388+
console.log(`\nCreated backup of ${performanceBackup.length} performances`);
389389

390390
// Demonstrate that slice doesn't modify the original
391-
console.log(\`Original array still has \${lastMonthPerformances.length} performances\`);
391+
console.log(`Original array still has ${lastMonthPerformances.length} performances`);
392392

393393
// Extract specific range for quarterly report
394394
const quarterlyData = lastMonthPerformances.slice(1, 3);
395-
console.log("\\nQuarterly report data:");
395+
console.log("\nQuarterly report data:");
396396
quarterlyData.forEach(performance => {
397-
console.log(\`- \${performance.venue}: $\${performance.revenue} revenue\`);
397+
console.log(`- ${performance.venue}: $${performance.revenue} revenue`);
398398
});
399-
\`\`\`
399+
```
400400

401-
Jordan nods approvingly, "So \`slice()\` lets you extract exactly the data you need without changing the original?"
401+
Jordan nods approvingly, "So `slice()` lets you extract exactly the data you need without changing the original?"
402402

403-
"Exactly!" Alex confirms. "The \`slice()\` method is **O(k) time complexity**, where k is the number of elements I'm extracting. It's perfect for getting specific ranges of data, creating backups, or extracting samples for analysis. The original data stays completely untouched."
403+
"Exactly!" Alex confirms. "The `slice()` method is **O(k) time complexity**, where k is the number of elements I'm extracting. It's perfect for getting specific ranges of data, creating backups, or extracting samples for analysis. The original data stays completely untouched."
404404

405405
---
406406
## ⏱️ **Alex's Data Analysis Challenge!**
407407
- 🔓 Uncomment the below code section in the editor 👉:
408-
\`\`\`js
408+
```js
409409
// ==============================
410410
// Exercise 3: Help Alex Analyze Performance Data
411411
// ==============================
412-
\`\`\`
412+
```
413413

414414
- Read the requirements written as comments in the code.
415415
- Implement the required logic.
@@ -428,7 +428,7 @@ Alex's reputation has grown to the point where they're now curating music festiv
428428

429429
"The festival director wants me to completely restructure the lineup," Alex explains to their team while reviewing the three-day festival schedule.
430430

431-
\`\`\`javascript
431+
```javascript
432432
// Day 1 of the music festival lineup
433433
let day1Lineup = [
434434
"Opening Ceremony",
@@ -466,7 +466,7 @@ let day2Lineup = [
466466
"Evening Headliner"
467467
];
468468

469-
console.log("\\nOriginal Day 2 lineup:", day2Lineup);
469+
console.log("\nOriginal Day 2 lineup:", day2Lineup);
470470

471471
// Remove three weak acts (positions 1, 2, 4) and replace with strong lineup
472472
let removedWeak = day2Lineup.splice(1, 2, "Rising Star Band", "Veteran Musician");
@@ -476,15 +476,15 @@ console.log("Improved lineup:", day2Lineup);
476476
// Remove another weak act and insert multiple strong acts
477477
day2Lineup.splice(4, 1, "Special Guest", "Surprise Collaboration", "Alex's Electronic Set");
478478
console.log("Final Day 2 lineup:", day2Lineup);
479-
\`\`\`
479+
```
480480

481-
"The \`splice()\` method is like a Swiss Army knife," Alex explains to the festival team. "It can remove elements, add elements, or do both at the same time. It's **O(n) time complexity** because elements after the splice point need to shift, but it gives me surgical precision for complex lineup changes."
481+
"The `splice()` method is like a Swiss Army knife," Alex explains to the festival team. "It can remove elements, add elements, or do both at the same time. It's **O(n) time complexity** because elements after the splice point need to shift, but it gives me surgical precision for complex lineup changes."
482482

483483
### The Art of Method Chaining - Elegant Data Pipelines
484484

485485
"Now for the real magic," Alex says, opening their laptop to show the team how to create sophisticated data processing pipelines.
486486

487-
\`\`\`javascript
487+
```javascript
488488
// Alex's complete song database with rich metadata
489489
const masterSongDatabase = [
490490
{ title: "Thunderstruck", genre: "rock", mood: "energetic", duration: 4.8, difficulty: "medium", year: 1990, popularity: 95 },
@@ -507,13 +507,13 @@ const weddingSetlist = masterSongDatabase
507507
title: song.title,
508508
duration: song.duration,
509509
arrangement: "acoustic guitar and vocals",
510-
specialNote: \`Perfect for \${song.mood} moments\`
510+
specialNote: `Perfect for ${song.mood} moments`
511511
}))
512512
.slice(0, 4); // Limit to 4 songs for intimate ceremony
513513

514514
console.log("Perfect Wedding Setlist:");
515515
weddingSetlist.forEach((song, index) => {
516-
console.log(\`\${index + 1}. \${song.title} (\${song.duration}min) - \${song.specialNote}\`);
516+
console.log(`${index + 1}. ${song.title} (${song.duration}min) - ${song.specialNote}`);
517517
});
518518

519519
// Create a rock festival setlist with popularity scoring
@@ -528,9 +528,9 @@ const rockFestivalSetlist = masterSongDatabase
528528
.sort((a, b) => b.festivalScore - a.festivalScore) // Sort by festival score
529529
.slice(0, 5); // Top 5 songs
530530

531-
console.log("\\nRock Festival Setlist (by crowd impact):");
531+
console.log("\nRock Festival Setlist (by crowd impact):");
532532
rockFestivalSetlist.forEach((song, index) => {
533-
console.log(\`\${index + 1}. \${song.title} (Score: \${song.festivalScore}, Response: \${song.expectedCrowdResponse})\`);
533+
console.log(`${index + 1}. ${song.title} (Score: ${song.festivalScore}, Response: ${song.expectedCrowdResponse})`);
534534
});
535535

536536
// Calculate total performance statistics using chaining
@@ -547,10 +547,10 @@ const performanceStats = masterSongDatabase
547547
// Finalize the statistics
548548
performanceStats.averagePopularity = (performanceStats.averagePopularity / performanceStats.songCount).toFixed(1);
549549

550-
console.log("\\nPerformance Statistics for Manageable Songs:");
551-
console.log(\`Total Duration: \${performanceStats.totalDuration.toFixed(1)} minutes\`);
552-
console.log(\`Average Popularity: \${performanceStats.averagePopularity}%\`);
553-
console.log(\`Song Count: \${performanceStats.songCount}\`);
550+
console.log("\nPerformance Statistics for Manageable Songs:");
551+
console.log(`Total Duration: ${performanceStats.totalDuration.toFixed(1)} minutes`);
552+
console.log(`Average Popularity: ${performanceStats.averagePopularity}%`);
553+
console.log(`Song Count: ${performanceStats.songCount}`);
554554
console.log("Genre Distribution:", performanceStats.genres);
555555

556556
// Create a dynamic setlist based on time constraints
@@ -581,11 +581,11 @@ thirtyMinuteSet.forEach(song => {
581581
song.cumulativeTime = runningTime.toFixed(1);
582582
});
583583

584-
console.log("\\n30-Minute Energetic Set:");
584+
console.log("\n30-Minute Energetic Set:");
585585
thirtyMinuteSet.forEach(song => {
586-
console.log(\`\${song.position}. \${song.title} (\${song.duration}min) - Running total: \${song.cumulativeTime}min\`);
586+
console.log(`${song.position}. ${song.title} (${song.duration}min) - Running total: ${song.cumulativeTime}min`);
587587
});
588-
\`\`\`
588+
```
589589

590590
"Method chaining is like conducting an orchestra," Alex explains with enthusiasm. "Each method is like a different section of musicians, and when you chain them together, you create a beautiful, complex performance from simple individual parts."
591591

@@ -597,11 +597,11 @@ Maya looks amazed, "So you can filter, transform, sort, and calculate all in one
597597

598598
## ⏱️ **Alex's Festival Curation Challenge!**
599599
- 🔓 Uncomment the below code section in the editor 👉:
600-
\`\`\`js
600+
```js
601601
// ==============================
602602
// Exercise 4: Help Alex Master Method Chaining and Advanced Array Operations
603603
// ==============================
604-
\`\`\`
604+
```
605605
- Read the requirements written as comments in the code.
606606
- Implement the required logic.
607607
- Click `Run Code` and inspect `📋 Console Output` window for correctness!
@@ -621,28 +621,28 @@ As Alex packs up after another successful festival, they reflect on how far they
621621
### 🎯 **The Complete Array Methods Toolkit**
622622

623623
#### **Core Modification Methods - The Foundation**
624-
- **\`push()\`** (O(1)): "Adding songs to the end of my setlist - always fast"
625-
- **\`pop()\`** (O(1)): "Removing the last song when time runs short - instant"
626-
- **\`unshift()\`** (O(n)): "Adding opening acts - powerful but requires shifting"
627-
- **\`shift()\`** (O(n)): "Removing finished acts - necessary but slower"
624+
- **`push()`** (O(1)): "Adding songs to the end of my setlist - always fast"
625+
- **`pop()`** (O(1)): "Removing the last song when time runs short - instant"
626+
- **`unshift()`** (O(n)): "Adding opening acts - powerful but requires shifting"
627+
- **`shift()`** (O(n)): "Removing finished acts - necessary but slower"
628628

629629
#### **Transformation Methods - The Creative Tools**
630-
- **\`map()\`** (O(n)): "Creating venue-specific versions of every song"
631-
- **\`filter()\`** (O(n)): "Selecting perfect songs for each occasion"
630+
- **`map()`** (O(n)): "Creating venue-specific versions of every song"
631+
- **`filter()`** (O(n)): "Selecting perfect songs for each occasion"
632632

633633
#### **Analysis Methods - The Business Intelligence**
634-
- **\`forEach()\`** (O(n)): "Processing each performance for reports and alerts"
635-
- **\`reduce()\`** (O(n)): "Calculating totals, averages, and complex statistics"
636-
- **\`slice()\`** (O(k)): "Extracting specific data ranges without changing originals"
634+
- **`forEach()`** (O(n)): "Processing each performance for reports and alerts"
635+
- **`reduce()`** (O(n)): "Calculating totals, averages, and complex statistics"
636+
- **`slice()`** (O(k)): "Extracting specific data ranges without changing originals"
637637

638638
#### **Advanced Manipulation - The Precision Tools**
639-
- **\`splice()\`** (O(n)): "Surgical editing of festival lineups and complex arrangements"
639+
- **`splice()`** (O(n)): "Surgical editing of festival lineups and complex arrangements"
640640

641641
### 🎸 **Alex's Method Selection Philosophy**
642642

643643
"Tonight taught me that choosing the right array method is like choosing the right instrument for a song," Alex muses while reviewing their performance analytics. "Each method has its perfect use case:"
644644

645-
\`\`\`javascript
645+
```javascript
646646
// Alex's decision framework for array methods
647647
class ArrayMethodSelector {
648648
static chooseMethod(task, dataSize, performanceNeeds) {
@@ -694,9 +694,9 @@ const optimizationTips = [
694694

695695
console.log("Alex's Array Method Mastery Guidelines:");
696696
optimizationTips.forEach((tip, index) => {
697-
console.log(\`\${index + 1}. \${tip}\`);
697+
console.log(`${index + 1}. ${tip}`);
698698
});
699-
\`\`\`
699+
```
700700

701701
### 🌟 **From Basic Operations to Advanced Data Processing**
702702

0 commit comments

Comments
 (0)