-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.ts
645 lines (507 loc) · 28.6 KB
/
app.ts
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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
// Exercise 1: Install Node.js, TypeScript and VS Code on your computer.
// Done
//Exercise 2:Personal Message: Store a person’s name in a variable, and print a message to that person. Your message should be simple, such as, “Hello Eric, would you like to learn some Python today?”
let personName: string = "Tehreem";
console.log(
`\nHello ${personName}, would you like to learn some Python today?\n`
);
// Exercise 3: Name Cases: Store a person’s name in a variable, and then print that person’s name in lowercase, uppercase, and titlecase.
let personName2: string = "tehreem";
console.log("lowercase:", personName2.toLowerCase());
console.log("Uppercase:", personName2.toUpperCase());
console.log(
"Titlecase:",
personName2
.split(" ")
.map((l: string) => l[0].toUpperCase() + l.substr(1))
.join(" ")
);
// Exercise 4:Famous Quote: Find a quote from a famous person you admire. Print the quote and the name of its author. Your output should look something like the following, including the quotation marks:
//Albert Einstein once said, “A person who never made a mistake never tried anything new.”
console.log(
"Nelson Mandela once said, “Education is the most powerful weapon which you can use to change the world.”"
);
//Exercise 5:Famous Quote 2: Repeat Exercise 4, but this time store the famous person’s name in a variable called famous_person. Then compose your message and store it in a new variable called message. Print your message.
let famouse_person: string = "Nelson Mandala";
let messag: string =
"“Education is the most powerful weapon which you can use to change the world.”";
console.log(`\n${famouse_person} once said,${messag}`);
// Exercise 6: Stripping Names: Store a person’s name, and include some whitespace characters at the beginning and end of the name. Make sure you use each character combination, "\t" and "\n", at least once. Print the name once, so the whitespace around the name is displayed. Then print the name after striping the white spaces.
const person_Name: string = " \n\tShahid Afridi\t\n ";
console.log(person_Name);
const without_spaces: string = person_Name.trim();
console.log(without_spaces);
//Exercise 7:Number Eight: Write addition, subtraction, multiplication, and division operations that each result in the number 8. Be sure to enclose your operations in print statements to see the results.
let addition: number = 5 + 3;
let subtraction: number = 10 - 2;
let multiplication: number = 2 * 4;
let division: number = 16 / 2;
//console.log(addition,subtraction,multiplication,division);
console.log(addition);
console.log(subtraction);
console.log(multiplication);
console.log(division);
//Exercise 8:You should create four lines that look like this: console.log(5 + 3)
//Your output should simply be four lines with the number 8 appearing once on each line.
console.log(4 + 4);
console.log(3 + 5);
console.log(6 + 2);
console.log(7 + 1);
//Exercise 9:Favorite Number: Store your favorite number in a variable. Then, using that variable, create a message that reveals your favorite number. Print that message.
let favorit_number: number = 8;
let Messag = "Here is your my favorite number" + "\t" + favorit_number;
console.log(Messag);
//Exercise 10:Adding Comments: Choose two of the programs you’ve written, and add at least one comment to each. If you don’t have anything specific to write because your programs are too simple at this point, just add your name and the current date at the top of each program file. Then write one sentence describing what the program does.
let Name: string = "Tehreem"; // here i am doing store name in a variable.
console.log(Name); //this program will print name.
// program written by: Tehreem;
// Current Date : 17-feb-2024;
//Exercise 11:Names: Store the names of a few of your friends in a array called names. Print each person’s name by accessing each element in the list, one at a time.
let names: string[] = ["Hajra", "shaheen", "Muskan", "fizza"];
/*
console.log(names[0]);
console.log(names[1]);
console.log(names[2]);
console.log(names[3]);
*/
for (var i = 0; i < names.length; i++) {
console.log(names[i]);
}
// Exercise 12: Greetings: Start with the array you used in Exercise 11, but instead of just printing each person’s name, print a message to them. The text of each message should be the same, but each message should be personalized with the person’s name.
let Names: string[] = ["hajra", "shaheen", "muskan", "fizza"];
for (let i = 0; i < Names.length; i++) {
console.log(Names[i] + "\tis my good friend");
}
//Exercise 13:Your Own Array: Think of your favorite mode of transportation, such as a motorcycle or a car, and make a list that stores several examples. Use your list to print a series of statements about these items, such as “I would like to own a Honda motorcycle.”
let transportation: string[] = [
"Spyder Car",
"Sport Bike",
"electric train",
"cycle",
];
for (let i = 0; i < transportation.length; i++) {
console.log(`I would like to own a` + "\t" + transportation[i]);
}
//Exercise 14:Guest List: If you could invite anyone, living or deceased, to dinner, who would you invite? Make a list that includes at least three people you’d like to invite to dinner. Then use your list to print a message to each person, inviting them to dinner.
let Guestlist: string[] = ["Arham", "Ayesha", "Taha"];
for (let i = 0; i < Guestlist.length; i++) {
console.log(`"Dear ${Guestlist[i]}," you are invited to dinner"`);
}
//Exercise 15: Changing Guest List: You just heard that one of your guests can’t make the dinner, so you need to send out a new set of invitations. You’ll have to think of someone else to invite.
let absent_guess: string = '"Arham';
console.log(absent_guess, ` is not coming.`);
let new_guest: string = "Sarim";
Guestlist[0] = new_guest; // update array add new guest
for (let i = 0; i < Guestlist.length; i++) {
console.log(`"Dear ${Guestlist[i]}," you are invited to dinner`);
}
//Exercise 16: More Guests: You just found a bigger dinner table, so now more space is available. Think of three more guests to invite to dinner.
console.log("Good News! I find big table so I am inviting 3 more guests.");
Guestlist.unshift("shaheen"); // add in starting of array
Guestlist.splice(3, 0, "Hajra"); // add in middle of array
Guestlist.push("Muskan"); // add in last of array
for (let guest of Guestlist) {
console.log(`Dear ${guest} you are invited to dinner `);
}
// Exercise 17: Shrinking Guest List: You just found out that your new dinner table won’t arrive in time for the dinner, and you have space for only two guests.
//• Start with your program from Exercise 16. Add a new line that prints a message saying that you can invite only two people for dinner.
console.log(
"sorry, I can not arrange big table. so I can only invite two people for diner\n\n"
);
//• Remove guests from your list one at a time until only two names remain in your list. Each time you pop a name from your list, print a message to that person letting them know you’re sorry you can’t invite them to dinner.
while (Guestlist.length > 2) {
let remove_guest = Guestlist.pop();
console.log(`"sorry ${remove_guest}, you are not invited for diner"`);
}
// • Print a message to each of the two people still on your list, letting them know they’re still invited.
for (let guests of Guestlist) {
console.log(`Dear ${guests} you are still invited to diner.`);
}
// • Remove the last two names from your list, so you have an empty list. Print your list to make sure you actually have an empty list at the end of your program.
Guestlist.splice(0, 2); // remove from array
console.log(Guestlist);
//Exercise 18: Seeing the World: Think of at least five places in the world you’d like to visit.
//• Store the locations in a array. Make sure the array is not in alphabetical order.
let visit_placess: string[] = ["Turky", "Dubai", "Soudi", "Pakistan", "Uk"];
//• Print your array in its original order.
console.log(`Orignal Order`, visit_placess);
//• Print your array in alphabetical order without modifying the actual list.
console.log(`Alphabetical Order`, [...visit_placess].sort());
//• Show that your array is still in its original order by printing it.
console.log(`Orignal Order`, visit_placess);
//• Print your array in reverse alphabetical order without changing the order of the original list.
console.log(`Reverse alphabatical order:`, [...visit_placess].sort().reverse());
//• Show that your array is still in its original order by printing it again.
console.log(`Orignal order after revers`, visit_placess);
//• Reverse the order of your list. Print the array to show that its order has changed.
visit_placess.reverse();
console.log(`Convert to revers order`, visit_placess);
//• Reverse the order of your list again. Print the list to show it’s back to its original order
visit_placess.reverse();
console.log(`back to original order`, visit_placess);
//• Sort your array so it’s stored in alphabetical order. Print the array to show that its order has been changed.
visit_placess.sort();
console.log(`sort in alphabetical order`, visit_placess);
//• Sort to change your array so it’s stored in reverse alphabetical order. Print the list to show that its order has changed.
visit_placess.sort().reverse();
console.log(`sorted in reverse alphabetical order;`, visit_placess);
//Exercise 19: Dinner Guests: Working with one of the programs from Exercises 14 through 18, print a message indicating the number of people you are inviting to dinner.
console.log(`Our Guest list is empty ${Guestlist.length}`);
//Exercise 20:Think of something you could store in a array. For example, you could make a list of mountains, rivers, countries, cities, languages, or anything else you’d like. Write a program that creates a list containing these items.
let placess_names: string[] = [
"pakistan",
"karachi",
"lahore",
"dubai",
"larkana",
];
placess_names.forEach((placess) => {
console.log(placess);
});
//Exercise 21:They think of something you could store in a TypeScript Object. Write a program that creates Objects containing these items.
let person: { name: string; country: string; age: number } = {
name: "Tehreem",
country: "pakistan",
age: 18,
};
console.log("person data ", person);
//Exercise 22:Intentional Error: If you haven’t received an array index error in one of your programs yet, try to make one happen. Change an index in one of your programs to produce an index error. Make sure you correct the error before closing the program.
const days: string[] = [
"sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"saturday",
];
console.log(days[7]); // intentional eror
console.log(days[6]);
// Exercise 23:Conditional Tests: Write a series of conditional tests. Print a statement describing each test and your prediction for the results of each test. Your code should look something like this:
// • Look closely at your results, and make sure you understand why each line evaluates to True or False.
// • Create at least 10 tests. Have at least 5 tests evaluate to True and another 5 tests evaluate to False.
let n_ame = "Arham";
console.log("is n_ame == 'Arham'? I predict True.");
console.log(n_ame == "Arham");
console.log("is n_ame === 'Arham'? I predict True.");
console.log(n_ame === "Arham");
console.log("is n_ame !== 'arham'? I predict True.");
console.log(n_ame !== "arham");
console.log("is n_ame != 'tehreem'? I predict True.");
console.log(n_ame != "tehreem");
console.log("is n_ame.lenght !== 45? I predict True.");
console.log(n_ame.length !== 45);
console.log("five test complet in true.\nNow start is false\n");
console.log(`is n_ame =="arham"? I predict false.`);
console.log(n_ame == "arham");
console.log(`is n_ame !=="Arham"? I predict false.`);
console.log(n_ame !== "Arham");
console.log(`is n_ame ==="arham"? I predict false.`);
console.log(n_ame === "arham");
console.log(`is n_ame !="Arham"? I predict false.`);
console.log(n_ame != "Arham");
console.log(`is n_ame.lenght == 20 ? I predict false.`);
console.log(n_ame.length == 20);
//Exercise 24: More Conditional Tests: You don’t have to limit the number of tests you create to 10. If you want to try more comparisons, write more tests. Have at least one True and one False result for each of the following:
let num1: string = "10";
let num2: string = "12";
//• Tests for equality and inequality with strings
console.log('"Inequality:"', num1 != num2);
console.log('"equality:"', num1 == num2);
//• Tests using the lower case function
let place: string = "new karachi";
let place1: string = "karachi";
console.log(
`" loweCase In true:"`,
place.toLowerCase() != place1.toLowerCase()
);
console.log(
`"loweCase In false:"`,
place.toLowerCase() == place1.toLowerCase()
);
//• Numerical tests involving equality and inequality, greater than and less than, greater than or equal to, and less than or equal to
let number: number = 30;
let number1: number = 25;
console.log(`"inequality:"`, number != number1);
console.log(`"equality:"`, number == number1);
console.log(`"Greater than:" `, number > number1);
console.log(`"Less than:"`, number < number1);
console.log(`"Greater than and equal to:"`, number >= number1);
console.log(`"Less than and equal to:"`, number <= number1);
//• Tests using "and" and "or" operators
console.log(`"And Operator:"`, number > number1 && number >= number1);
console.log(`"Or Operator:"`, number < number1 || number <= number1);
// Test whether an item is in a array
let countrys: string[] = ["pakistan", "india", "jarmani", "paris", "uk"];
if (countrys.includes("paris")) {
console.log("paris, is in a array");
}
//• Test whether an item is not in a array
if (!countrys.includes("france")) {
console.log("france is not in a array");
}
//Exercise 25:Alien Colors #1: Imagine an alien was just shot down in a game. Create a variable called alien_color and assign it a value of 'green', 'yellow', or 'red'.
let alien_color: string = "green";
if (alien_color == "green") {
console.log("congratulations! you are earn 5 points.");
}
alien_color = "red"; // update value of alien_color
if (alien_color == "green") {
console.log("congratulations! you are earn 5 points.");
} else {
console.log("No Output");
}
// Exercise 26:Alien Colors #2: Choose a color for an alien as you did in Exercise 25, and write an if-else chain.
//• If the alien’s color is green, print a statement that the player just earned 5 points for shooting the alien.
//• If the alien’s color isn’t green, print a statement that the player just earned 10 points.
//• Write one version of this program that runs the if block and another that runs the else block.
alien_color = "green"; // update value
if (alien_color == "green") {
console.log("the player just earned 5 points for shooting the alien.");
} else {
console.log("the player just earned 10 points for shooting the alien.");
}
alien_color = "red"; // update value
if (alien_color == "green") {
console.log("the player just earned 5 points for shooting the alien.");
} else {
console.log("the player just earned 10 points for shooting the alien.");
}
// Exercise 27:Alien Colors #3: Turn your if-else chain from Exercise 5-4 into an if-else chain.
//• If the alien is green, print a message that the player earned 5 points.
alien_color = "green"; // update value
if (alien_color == "green") {
console.log("the player earned 5 points.");
}
//• If the alien is yellow, print a message that the player earned 10 points.
alien_color = "yellow"; // update value
if (alien_color == "yellow") {
console.log("the player earned 10 points.");
}
//• If the alien is red, print a message that the player earned 15 points.
alien_color = "red"; // update value
if (alien_color == "red") {
console.log("the player earned 15 points.");
}
//• Write three versions of this program, making sure each message is printed for the appropriate color alien.
// Exercise 28:Stages of Life: Write an if-else chain that determines a person’s stage of life. Set a value for the variable age, and then:
let age: number = 18;
if (age < 2) {
console.log("you are a baby");
} else if (age < 4) {
console.log("you are a toddler");
} else if (age < 13) {
console.log("you are a kid");
} else if (age < 20) {
console.log("you are a teenager");
} else if (age < 65) {
console.log("you are a adult");
} else {
console.log("you are elder");
}
// Exercise 29:Favorite Fruit: Make a array of your favorite fruits, and then write a series of independent if statements that check for certain fruits in your array.
// • Make a array of your three favorite fruits and call it favorite_fruits.
// • Write five if statements. Each should check whether a certain kind of fruit is in your array. If the fruit is in your array, the if block should print a statement, such as You really like bananas!
let favorite_fruits: string[] = ["apple", "mango", "orang"];
if (favorite_fruits.includes("apple")) {
console.log("you really like apple!");
}
if (favorite_fruits.includes("mango")) {
console.log("you really like mango!");
}
if (favorite_fruits.includes("orang")) {
console.log("you realy like orang!");
}
if (favorite_fruits.includes("bnana")) {
console.log(" bnana is not in array.");
}
if (favorite_fruits.includes("strawberry")) {
console.log("strawberry is not in array.");
}
// Exercise 30:Hello Admin: Make a array of five or more usernames, including the name 'admin'. Imagine you are writing code that will print a greeting to each user after they log in to a website. Loop through the array, and print a greeting to each user:
// • If the username is 'admin', print a special greeting, such as Hello admin, would you like to see a status report?
// • Otherwise, print a generic greeting, such as Hello Eric, thank you for logging in again.
let username: string[] = ["admin", "arham", "eric", "taha", "sarim"];
for (let i = 0; i < username.length; i++) {
if (username[i] == "admin") {
console.log(`HELLO Admin, would you like to see a stutas report?`);
} else {
console.log(`HELLO ${username[i]}, thank you for logging in again`);
}
}
// Exercise 31:No Users: Add an if test to Exercise 28 to make sure the list of users is not empty.
//• If the list is empty, print the message We need to find some users!
//• Remove all of the usernames from your array, and make sure the correct message is printed.
if (username.length == 0) {
console.log(`we need to find some users!`);
} else {
username = [];
console.log("All user name has been remove.", username.length);
}
// Exercise 32: Checking Usernames: Do the following to create a program that simulates how websites ensure that everyone has a unique username.
// • Make a list of five or more usernames called current_users.
const current_users: string[] = ["Eric", "Arham", "Hamza", "Taha", "Daniyal"];
//• Make another list of five usernames called new_users. Make sure one or two of the new usernames are also in the current_users list.
const new_users: string[] = ["Zeshan", "Kashan", "Daniyal", "Farhan", "Arham"];
// Convert current usernames to lowercase for case insensitive comparison
const current_users_lower = current_users.map((user) => user.toLowerCase());
//• Loop through the new_users list to see if each new username has already been used. If it has, print a message that the person will need to enter a new username. If a username has not been used, print a message saying that the username is available.
for (let i = 0; i < new_users.length; i++) {
//• Make sure your comparison is case insensitive. If 'John' has been used, 'JOHN' should not be accepted.
// Convert the new username to lowercase for case insensitive comparison
const new_username = new_users[i].toLowerCase();
// Check if the new username exists in the current_users list (case insensitive)
if (current_users_lower.includes(new_username)) {
console.log(`${new_users[i]} has been used. Please enter a new username.`);
} else {
console.log(`${new_users[i]} is available.`);
}
}
//Exercise 33:Ordinal Numbers: Ordinal numbers indicate their position in a array, such as 1st or 2nd. Most ordinal numbers end in th, except 1, 2, and 3.
//• Store the numbers 1 through 9 in a array.
let numbers: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9];
// • Loop through the array.
for (let i = 0; i < numbers.length; i++) {
//Use an if-else chain inside the loop to print the proper ordinal ending for each number. Your output should read "1st 2nd 3rd 4th 5th 6th 7th 8th 9th", and each result should be on a separate line.
let ordinal = "";
if (numbers[i] == 1) {
ordinal = "st";
} else if (numbers[i] == 2) {
ordinal = "nd";
} else if (numbers[i] == 3) {
ordinal = "rd";
} else {
ordinal = "th";
}
console.log(`${numbers[i]}${ordinal}`);
}
// Exercise 34:Pizzas: Think of at least three kinds of your favorite pizza. Store these pizza names in a array, and then use a for loop to print the name of each pizza.
let favorite_pizza: string[] = ["pepperoni", "margherita", "vegatarian"];
for (let i = 0; i < favorite_pizza.length; i++) {
//• Modify your for loop to print a sentence using the name of the pizza instead of printing just the name of the pizza. For each pizza you should have one line of output containing a simple statement like I like pepperoni pizza.
console.log(`I like ${favorite_pizza[i]} pizza.`);
}
//• Add a line at the end of your program, outside the for loop, that states how much you like pizza. The output should consist of three or more lines about the kinds of pizza you like and then an additional sentence, such as I really love pizza!
console.log(`I really love pizza`);
// Exersise 35: Animals: Think of at least three different animals that have a common characteristic. Store the names of these animals in a list, and then use a for loop to print out the name of each animal.
let animals: string[] = ["dog", "cat", "rabbit"];
for (let i = 0; i < animals.length; i++) {
//. • Modify your program to print a statement about each animal, such as A dog would make a great pet
console.log(`A ${animals[i]} would make a great pet.`);
}
// • Add a line at the end of your program stating what these animals have in common. You could print a sentence such as Any of these animals would make a great pet!
console.log("Any of these animals would make a great pet!");
//Exercise 36:T-Shirt: Write a function called make_shirt() that accepts a size and the text of a message that should be printed on the shirt. The function should print a sentence summarizing the size of the shirt and the message printed on it. Call the function.
function make_shirt(size: string, message: string) {
console.log(` The shirt size is ${size} and it says ${message}.`);
}
make_shirt("T", "I love pakistan");
// Exercise 37:Large Shirts: Modify the make_shirt() function so that shirts are large by default with a message that reads I love TypeScript. Make a large shirt and a medium shirt with the default message, and a shirt of any size with a different message.
function Make_shirt(size: string = "T", messag: string = " I Love typescript") {
console.log(`The shirt size is ${size} and it says ${messag}`);
}
Make_shirt();
Make_shirt("M");
Make_shirt("l", "best of luck");
// Exercise 38:Cities: Write a function called describe_city() that accepts the name of a city and its country. The function should print a simple sentence, such as Karachi is in Pakistan. Give the parameter for the country a default value. Call your function for three different cities, at least one of which is not in the default country.
function describe_city(city: string, country: string = "unknown") {
console.log(`${city} is in ${country}`);
}
describe_city("larkana", "pakistan");
describe_city("london", "united kingdom");
describe_city("paris");
// Exercise 39:City Names: Write a function called city_country() that takes in the name of a city and its country. The function should return a string formatted like this:"Lahore, Pakistan"
function city_country(city: string, country: string) {
return `"${city} , ${country}"`;
}
//Call your function with at least three city-country pairs, and print the value that’s returned.
console.log(city_country("karachi", "pakistan"));
console.log(city_country("bambai", "india"));
console.log(city_country("Tokyo", "japan"));
//Exercise 40:Album: Write a function called make_album() that builds a Object describing a music album.
// The function should take in an artist name and an album title, and it should return a Object containing these two pieces of information.
// Use the function to make three dictionaries representing different albums. Print each return value to show that Objects are storing the album information correctly.
// Add an optional parameter to make_album() that allows you to store the number of tracks on an album. If the calling line includes a value for the number of tracks, add that value to the album’s Object.
// Make at least one new function call that includes the number of tracks on an album.
function make_album(
artist: string,
album: string,
tracks?: number
): { artist: string; album: string; tracks?: number } {
const albumObj: { artist: string; album: string; tracks?: number } = {
artist: artist,
album: album,
};
if (tracks) {
albumObj.tracks = tracks;
}
return albumObj;
}
console.log(make_album("Taylor Swift", "Fearless"));
console.log(make_album("Ed Sheeran", "Divide", 12));
console.log(make_album("Adele", "25", 10));
//Exercise 41:Magicians: Make a array of magician’s names. Pass the array to a function called show_magicians(), which prints the name of each magician in the array.
let magicians: string[] = [
"Harry Houdini",
"David Blaine",
"David Copperfield",
"Ricky Jay",
];
function show_magicians(Magicians: string[]) {
for (let i = 0; i < Magicians.length; i++) {
console.log(Magicians[i]);
}
}
show_magicians(magicians);
// Exercise 42:Great Magicians: Start with a copy of your program from Exercise 39. Write a function called make_great() that modifies the array of magicians by adding the phrase the Great to each magician’s name. Call show_magicians() to see that the list has actually been modified.
function make_great(magicians: string[]) {
for (let i = 0; i < magicians.length; i++) {
console.log(` ${magicians[i]} the great`);
}
}
make_great(magicians);
show_magicians(magicians);
//Exercise 43:Unchanged Magicians: Start with your work from Exercise 40. Call the function make_great() with a copy of the array of magicians’ names. Because the original array will be unchanged, return the new array and store it in a separate array. Call show_magicians() with each array to show that you have one array of the original names and one array with the Great added to each magician’s name.
function make_great2(magicians: string[]) {
let great_magicians: string[] = magicians.map(
(magicians) => `The Great ${magicians}`
);
return great_magicians;
}
let great_magicians: string[] = make_great2(magicians);
show_magicians(magicians);
show_magicians(great_magicians);
//Exercise 44:Sandwiches: Write a function that accepts a array of items a person wants on a sandwich. The function should have one parameter that collects as many items as the function call provides, and it should print a summary of the sandwich that is being ordered. Call the function three times, using a different number of arguments each time.
function make_sandwich(...items: string[]) {
console.log("sandwich Order");
for (let i = 0; i < items.length; i++) {
console.log(`-${items[i]}`);
}
console.log("enjoy your sandwiches");
}
make_sandwich("Turkey", "Lettuce", "Tomato", "Mayonnaise");
make_sandwich("Ham", "Cheese");
make_sandwich("Peanut Butter");
//Exercise 45:
// Define an interface for the Car object
interface Car {
manufacturer: string;
model: string;
options: { [key: string]: any }; // Options can have arbitrary keys and values
}
// Define the make_car function
function make_car(
manufacturer: string,
model: string,
...options: { [key: string]: any }[]
): Car {
// Initialize a car object
const car: Car = {
manufacturer,
model,
...Object.assign({},...options)
};
return car;
}
const car = make_car("Toyota", "Corolla", { color: "blue" }, { sunroof: true });
console.log(car);