From 9231627b6338fa36ad54e4ffe25a7d436869ac19 Mon Sep 17 00:00:00 2001 From: Sanjib Roy Date: Tue, 17 Mar 2020 03:51:43 +0530 Subject: [PATCH 1/4] push answers --- closure/closure.js | 89 +++++++++++++ closure/closure.md | 15 ++- higher-order-functions/eloquent/exercise.js | 22 ++++ higher-order-functions/exercise.js | 139 ++++++++++++++++++-- practice/closure.md | 38 +++++- practice/hoisting.md | 15 ++- practice/scope.md | 106 ++++++++++++++- 7 files changed, 399 insertions(+), 25 deletions(-) diff --git a/closure/closure.js b/closure/closure.js index e69de29..a6be201 100644 --- a/closure/closure.js +++ b/closure/closure.js @@ -0,0 +1,89 @@ +// Immidiately Call the blab function +let str = "ABCD"; + +function nonsense(string) { + let blab = (function () { + alert(string); + })(); +} + +nonsense(str); + + + + +// Call blab using setTimeout + +let str = "ABCD"; + +function nonsense(string) { + let blab = function () { + alert(string); + }; + + window.setTimeout(blab, 2000); +} + +nonsense(str); + +// Return blab + +let str = "ABCD"; +let str2 = "AltCampus"; + +function nonsense(string) { + let blab = function () { + alert(string); + }; + + return blab; +} +let blabLater = nonsense(str); +let blabAgainLater = nonsense(str2); + +// Display firstName and lastName both + +var lastNameTrier = function(firstName){ + + var innerFunction = function(lastName) { + console.log(firstName +" "+lastName); + }; + return innerFunction; +}; + +var firstNameFarmer = lastNameTrier('Farmer'); //logs nothing +firstNameFarmer('Brown'); //logs 'Farmer Brown' + + + + +// Write or erase a story + +function storyWriter() { + let obj = { + + story : "", + + addWords : function(words) { + obj.story += words; + return obj.story; + }, + + erase : function() { + obj.story = ""; + return obj.story; + } + } + + return obj; + } + + + var farmLoveStory = storyWriter(); + farmLoveStory.addWords('There was once a lonely cow.'); // 'There was once a lonely cow.' + farmLoveStory.addWords('It saw a friendly face.'); //'There was once a lonely cow. It saw a friendly face.' + + var storyOfMyLife = storyWriter(); + storyOfMyLife.addWords('My code broke.'); // 'My code broke.' + storyOfMyLife.addWords('I ate some ice cream.'); //'My code broke. I ate some ice cream.' + storyOfMyLife.erase(); // '' \ No newline at end of file diff --git a/closure/closure.md b/closure/closure.md index 10315e8..82c7254 100644 --- a/closure/closure.md +++ b/closure/closure.md @@ -6,7 +6,7 @@ var blab = function(){ alert(string); }; - ``` + ``` 1. In your function, `nonsense`, change the immediate call to a setTimeout so that the call to `blab` comes after 2 seconds. The `blab` function itself should stay the same as before. @@ -16,7 +16,9 @@ 1. Write a function with a closure. The first function should only take one argument, someone's first name, and the inner function should take one more argument, someone's last name. The inner function should console.log both the first name and the last name. - ```javascript + +```javascript + var lastNameTrier = function(firstName){ //does stuff @@ -27,7 +29,9 @@ }; var firstNameFarmer = lastNameTrier('Farmer'); //logs nothing firstNameFarmer('Brown'); //logs 'Farmer Brown' - ``` + +``` + This function is useful in case you want to try on different last names. For example, I could use firstName again with another last name: ```javascript @@ -37,7 +41,8 @@ 1. Create a `storyWriter` function that returns an object with two methods. One method, `addWords` adds a word to your story and returns the story while the other one, `erase`, resets the story back to an empty string. Here is an implementation: - ```javascript +```javascript + var farmLoveStory = storyWriter(); farmLoveStory.addWords('There was once a lonely cow.'); // 'There was once a lonely cow.' farmLoveStory.addWords('It saw a friendly face.'); //'There was once a lonely cow. It saw a friendly face.' @@ -47,4 +52,4 @@ storyOfMyLife.addWords('I ate some ice cream.'); //'My code broke. I ate some ice cream.' storyOfMyLife.erase(); // '' - ``` \ No newline at end of file +``` \ No newline at end of file diff --git a/higher-order-functions/eloquent/exercise.js b/higher-order-functions/eloquent/exercise.js index 01f23cb..350765d 100644 --- a/higher-order-functions/eloquent/exercise.js +++ b/higher-order-functions/eloquent/exercise.js @@ -2,10 +2,26 @@ let arrays = [[1, 2, 3], [4, 5], [6]]; // Your code here. + +function flatArray(array) { + return array.reduce( (acc, cv) => { + acc = acc.concat(cv); + return acc; + },[] ); +} + // → [1, 2, 3, 4, 5, 6] // Challenge 2. Your own loop // Your code here. +function loop(limit, conditionCheck, decrement, display) { + + while(conditionCheck(limit)) { + display(limit); + limit = decrement(limit); + } + +} loop(3, n => n > 0, n => n - 1, console.log); // → 3 @@ -15,6 +31,12 @@ loop(3, n => n > 0, n => n - 1, console.log); // Challenge 3. Everything function every(array, test) { // Your code here. + for(let i = 0; i < array.length; i++) { + if( !test(array[i]) ) { + return false; + } + } + return true; } console.log(every([1, 3, 5], n => n < 10)); diff --git a/higher-order-functions/exercise.js b/higher-order-functions/exercise.js index 927e3d3..349a73d 100644 --- a/higher-order-functions/exercise.js +++ b/higher-order-functions/exercise.js @@ -1,24 +1,57 @@ // Challenge 1 -function addTwo(num) {} +function addTwo(num) { + return num + 2; +} // To check if you've completed it, uncomment these console.logs! // console.log(addTwo(3)); // console.log(addTwo(10)); // Challenge 2 -function addS(word) {} +function addS(word) { + return word + 's'; +} // uncomment these to check your work // console.log(addS('pizza')); // console.log(addS('bagel')); // Challenge 3 -function map(array, callback) {} +function map(array, callback) { + let index = 0; + let newArray = []; + while(newArray.length < array.length) { + newArray.push(callback(array[index], index, array)); + index++; + } + return newArray; +} + +function addTwo(num) { + return num + 2; +} + // console.log(map([1, 2, 3], addTwo)); // Challenge 4 -function forEach(array, callback) {} + +let alphabet = ""; +function forEach(array, callback) { + let index = 0; + + while(index < array.length) { + callback(array[index],index, array); + index++; + } + +} + +var letters = ['a', 'b', 'c', 'd']; + +forEach(letters,(char) => alphabet += char); + +console.log(alphabet) // see for yourself if your forEach works! @@ -27,31 +60,117 @@ function forEach(array, callback) {} //-------------------------------------------------- //Extension 1 -function mapWith(array, callback) {} +function mapWith(array, callback) { + let newArray = []; + array.forEach(el => newArray.push( callback(el) )); + return newArray; +} + +function multiplyByTwo(el) { + return el * 2; +} + +var arr = [1, 2, 3, 4, 5]; + + +console.log(mapWith(arr,multiplyByTwo)); //Extension 2 -function reduce(array, callback, initialValue) {} +function reduce(array, callback, initialValue = array[0]) { + let ans; + for(let i = 0; i < array.length; i++) { + initialValue = callback(initialValue, array[i], i, array); + } + ans = initialValue; + return ans; +} + +function add(acc, cv) { + return acc+cv; +} + + +let array = [1, 2, 3, 4]; + +console.log(reduce(array, add, 0)); + //Extension 3 -function intersection(arrays) {} +function intersection(arrays) { + let ans; + let arr = arrays.flat(); + ans = arr.reduce((acc, cv, index) => { + + if(arr.indexOf(cv,index+1)!= -1 && !acc.includes(cv)) { + acc.push(cv); + } + return acc; + }, []); + return ans; +} // console.log(intersection([5, 10, 15, 20], [15, 88, 1, 5, 7], [1, 10, 15, 5, 20])); // should log: [5, 15] //Extension 4 -function union(arrays) {} + +function union(arrays) { + let ans; + let arr = arrays.flat(); + ans = arr.reduce((acc, cv, index) => { + + if(!acc.includes(cv)) { + acc.push(cv); + } + return acc; + }, []); + return ans; +} // console.log(union([5, 10, 15], [15, 88, 1, 5, 7], [100, 15, 10, 1, 5])); // should log: [5, 10, 15, 88, 1, 7, 100] //Extension 5 -function objOfMatches(array1, array2, callback) {} +function objOfMatches(array1, array2, callback) { + + let obj = callback(array1, array2); + return obj; +} + + function getObj(array1, array2) { + + let copyArray2 = array2.map(el => el.toUpperCase()); + + return array1.reduce( (acc, cv) => { + let pos = copyArray2.indexOf(cv.toUpperCase()); + + if(pos !== -1 && !Object.keys(acc).includes(cv)) { + acc[cv] = array2[pos]; + } + + return acc; + },{}); + + } + + + let array1 = ['hi', 'howdy', 'bye', 'later', 'hello']; + let array2 = ['HI', 'Howdy', 'BYE', 'LATER', 'hello']; + + console.log(objOfMatches(array1, array2, getObj)); // console.log(objOfMatches(['hi', 'howdy', 'bye', 'later', 'hello'], ['HI', 'Howdy', 'BYE', 'LATER', 'hello'], function(str) { return str.toUpperCase(); })); // should log: { hi: 'HI', bye: 'BYE', later: 'LATER' } //Extension 6 -function multiMap(arrVals, arrCallbacks) {} +function multiMap(arrVals, arrCallbacks) { + let obj = arrVals.reduce( (acc, cv) => { + acc[cv] = arrCallbacks.map(el=> el(cv)) + return acc; + },{}) + + return obj +} // console.log(multiMap(['catfood', 'glue', 'beer'], [function(str) { return str.toUpperCase(); }, function(str) { return str[0].toUpperCase() + str.slice(1).toLowerCase(); }, function(str) { return str + str; }])); // should log: { catfood: ['CATFOOD', 'Catfood', 'catfoodcatfood'], glue: ['GLUE', 'Glue', 'glueglue'], beer: ['BEER', 'Beer', 'beerbeer'] } diff --git a/practice/closure.md b/practice/closure.md index 80cec16..97a1ea4 100644 --- a/practice/closure.md +++ b/practice/closure.md @@ -5,6 +5,16 @@ ```js // Your code goes here +function multiplyBy(num1) { + + function double(num2) { + return num1 * num2; + } + + return double; + +} + const double = multiplyBy(2); const final = double(15); // final should be 30 ``` @@ -14,6 +24,15 @@ const final = double(15); // final should be 30 ```js // Your code goes here +function fullName(firstName) { + + function name(lastName) { + return firstName + lastName; + } + + return concatName; +} + const name = fullName("Will"); const final = name("Smith"); // final should be "Will Smith" ``` @@ -23,6 +42,11 @@ const final = name("Smith"); // final should be "Will Smith" ```js function isInBetween(a, b) { // your code goes here + function check(num) { + return num >= a && num <= b ; + } + + return check; } const isChild = isInBetween(10, 100); @@ -36,6 +60,12 @@ isChild(103); // false ```js function letsWishThem(greeting) { // your code goes here + function constructMessage(message) { + return greeting +" "+ message; + } + + return constructMessage; + } const callWithHey = letsWishThem("Hey"); @@ -63,8 +93,14 @@ cricket(); // Your score of Cricket is 2 6. Write a function called `getCard` which takes one of these options (club, spade, heart, dimond) returns a function calling that function returns random card (2,3,4,5,6,7,8,9,10,J, Q, K, A) of that suit. ```js -function getCard(suit) { +function addGame(suit) { // your code goes here + let card = [2,3,4,5,6,7,8,9,10,'J', 'Q', 'K', 'A']; + function getAns() { + let num = Math.floor(Math.random() * card.length - 1); + return `Card is : ${card[num]} ${suit}` + }; + return getAns; } // Output diff --git a/practice/hoisting.md b/practice/hoisting.md index 18c9f2b..b1ff85d 100644 --- a/practice/hoisting.md +++ b/practice/hoisting.md @@ -5,19 +5,20 @@ ```js console.log(animal); var animal = "monkey"; -// Output or Error Message +// Output : undefined + ``` ```js console.log(animal); let animal = "monkey"; -// Output or Error Message +// Error Message : animal is not defined; ``` ```js console.log(animal); const animal = "monkey"; -// Output or Error Message +// Error Message : animal is not defined; ``` ```js @@ -25,7 +26,7 @@ function sayHello(msg) { alert(msg); } sayHello("Hey Everyone"); -// Output or Error Message +// Output : It'll open the modal window and display the value of msg which is "Hey Everyone" ``` ```js @@ -33,7 +34,7 @@ sayHello("Hey Everyone"); function sayHello(msg) { alert(msg); } -// Output or Error Message +// Output : It'll open the modal window and display the value of msg which is "Hey Everyone" ``` ```js @@ -41,7 +42,7 @@ sayHello("Hey Everyone"); var sayHello = msg => { alert(msg); }; -// Output or Error Message +// Error Message : sayHello is not a function. ``` ```js @@ -49,4 +50,6 @@ sayHello("Hey Everyone"); let sayHello = msg => { alert(msg); }; + +// Error Message : sayHello is not defined. ``` diff --git a/practice/scope.md b/practice/scope.md index c5f960b..ad1f3c1 100644 --- a/practice/scope.md +++ b/practice/scope.md @@ -8,6 +8,8 @@ const lastName = "Stark"; var knownAs = "no one"; console.log(window.firstName, window.lastName, window.knownAs); + +//Output : undefined, undefined, "no one" ``` 2. Guess the output: @@ -22,17 +24,25 @@ function fullName(a, b) { } console.log(window.fullName(firstName, lastName)); + +// Output : "AryaStark" ``` 3. Make a Execution Context Diagram for the following JS and write the output. ```js + fucntion addOne(num){ return num + 1; } + var one = addOne(0); var two = addOne(1); console.log(one, two); + +// Output : 1 +// 2 + ``` 4. Make a Execution Context Diagram for the following JS and write the output. @@ -44,6 +54,10 @@ fucntion addOne(num){ } var two = addOne(1); console.log(one, two); + +// Output : 1 +// 2 + ``` 5. Make a Execution Context Diagram for the following JS and write the output. @@ -55,6 +69,8 @@ fucntion addOne(num){ } var two = addOne(1); console.log(two); + +// Output : ``` 6. Make a Execution Context Diagram for the following JS and write the output. @@ -90,6 +106,8 @@ function isAwesome() { console.log(awesome); } isAwesome(); + +// Output: undefined ``` 9. What will be the output of the following @@ -103,6 +121,8 @@ function isAwesome() { console.log(awesome); } isAwesome(); + +// Output: true ``` 10. What will be the output of the following @@ -116,11 +136,14 @@ function isAwesome() { console.log(awesome); } isAwesome(); + +// Output: undefined ``` 11. What will be the output of the following ```js + let firstName = "Arya"; const lastName = "Stark"; var knownAs = "no one"; @@ -130,6 +153,8 @@ function fullName(a, b) { } const name = fullName(firstName, lastName); console.log(name); + +// Output: "AryaStark" ``` 12. What will be the output of the following @@ -144,6 +169,8 @@ function fullName(a, b) { } const name = fullName(firstName, lastName); console.log(name); + +// Output: "AryaStark" ``` 13. Guess the output of the code below with a reason. @@ -155,6 +182,9 @@ function sayHello() { sayHello(); console.log(name); + +// Error: name is not defined. Because let is a block scoped and we can't access it out of the block. + ``` 14. Guess the output of the code below with a reason. @@ -164,6 +194,9 @@ if (true) { var name = "Arya Stark"; } console.log(name); + +// Output : "Arya Stark" [Because var is function scoped and if it is not declared inside any function then it'll get stored inside the window object.] + ``` 15. Guess the output of the code below with a reason. @@ -173,6 +206,8 @@ if (true) { let name = "Arya Stark"; } console.log(name); + +// Error: name is not defined. Because let is a block scoped and we can't access it out of the block. ``` 16. Guess the output of the code below with a reason. @@ -182,6 +217,8 @@ for (var i = 0; i < 20; i++) { // } console.log(i); + +// Output: 20; ``` 17. Guess the output of the code below with a reason. @@ -191,6 +228,8 @@ for (let i = 0; i < 20; i++) { // } console.log(i); + +// Error: i is not defined. Because let is a block scoped and we can't access it out of the block. ``` 18. Guess the output of the code below with a reason. @@ -200,6 +239,7 @@ for (var i = 0; i < 20; i++) { setTimeout(() => console.log(i, "first"), 100); } console.log(i, "second"); + ``` 19. Guess the output of the code below with a reason. @@ -220,6 +260,9 @@ function sample() { } console.log(username); } + +// Var is function scoped so we can access it anywhere inside the function and because of closure the console.log gets the value of username. + ``` 21. Guess the output and the reason behind that. @@ -231,6 +274,8 @@ function sample() { } console.log(username); } + +// Error: username is not defined. Because let is block scoped and we can't access it outside the block(Here if block). ``` 22. Guess the output and the reason behind that. @@ -244,6 +289,13 @@ function sample() { } console.log(username, "second"); } + +// Output :"John Snow" +// "John Snow" +// "second" + +// var is function scoped so we can access it anywhere inside the function where it is declared. Variable declared with var can be declared more than once and each declaration it'll overwrite the previous value. + ``` 23. Guess the output and the reason behind that. @@ -257,6 +309,16 @@ function sample() { } console.log(username, "second"); } + +// Output: "John Snow" +// "first" +// "Arya Stark" +// "Second" + +// let is block scoped so we can't access it outside the block. Here inside the if statement the username has no link with the outer username variable because they are belonging in different blocks. It is a totally new variable for this if block . + + + ``` 24. Guess the output and the reason behind that. @@ -296,6 +358,13 @@ if (true) { let username = "Hello World!"; myFunc(); } + +// Output: username is not defined +// "First" +// "Hello World" +// "Second" + +// let does not initialize variable during declaration phase. As we can't use any uninitialized variable that's why it'll throw an error. ``` 27. Guess the output and the reason behind that. @@ -304,12 +373,16 @@ if (true) { function outer() { let movie = "Mad Max: Fury Road"; function inner() { - console.log("I love this movie called ${movie.toUpperCase()}"); + console.log(`I love this movie called ${movie.toUpperCase()}`); } inner(); } outer(); + +// Output: "I love this movie called MAD MAX: FURY ROAD" + +// Because of closure it gets the value of movie. ``` 28. Guess the output and the reason behind that. @@ -319,12 +392,16 @@ function outer() { let movie = "Mad Max: Fury Road"; function inner() { let movie = "Before Sunrise"; - console.log("I love this movie called ${movie.toUpperCase()}"); + console.log(`I love this movie called ${movie.toUpperCase()}`); } inner(); } outer(); + +// Output: "I love this movie called Before Sunrise" + +// inner function will search its memory first. ``` 29. Guess the output and the reason behind that. @@ -344,6 +421,11 @@ function outer() { } outer(); + +// Output: "I love this movie called Gone Girl" + +// Because extraInner function always searches for the variable movie in its memory first. + ``` 30. Execute all the functions inside `allFunctions` variable using any loop. (Hint: use for of loop functions are object) @@ -356,13 +438,22 @@ const sub = (a, b) => { return a - b; }; const multiply = (a, b) => { - return a + b; + return a * b; }; const divide = (a, b) => { return a / b; }; +// --- + let allFunctions = [add, sub, multiply, divide]; +let a = 10; +let b = 5; + +for(let fn of allFunctions) { + console.log( fn(a, b) ); +} + ``` 31. You have to pass 10 and 12 as initial value and find the final output when you pass the return value of one function as an input to the next function in the array `allFunctions`. @@ -382,4 +473,13 @@ const divide = (a, b) => { }; let allFunctions = [add, add, add, add, add, sub, sub, multiply, divide]; + +let a = 10; +let b = 12; + +for(let fn of allFunctions) { + a = fn(a, b); +} + + ``` From 32d7d711623d258b8309d0804e9be8d95a591ae6 Mon Sep 17 00:00:00 2001 From: Sanjib Roy Date: Tue, 17 Mar 2020 23:06:24 +0530 Subject: [PATCH 2/4] Push Answers --- higher-order-functions/exercise.js | 4 ++-- higher-order-functions/exercise.md | 6 ++++++ practice/closure.md | 17 +++++++++++++++++ practice/scope.md | 13 ++++++++++++- 4 files changed, 37 insertions(+), 3 deletions(-) diff --git a/higher-order-functions/exercise.js b/higher-order-functions/exercise.js index 349a73d..0ded5eb 100644 --- a/higher-order-functions/exercise.js +++ b/higher-order-functions/exercise.js @@ -4,8 +4,8 @@ function addTwo(num) { } // To check if you've completed it, uncomment these console.logs! -// console.log(addTwo(3)); -// console.log(addTwo(10)); +console.log(addTwo(3)); +console.log(addTwo(10)); // Challenge 2 function addS(word) { diff --git a/higher-order-functions/exercise.md b/higher-order-functions/exercise.md index 9764c13..e3beb2b 100644 --- a/higher-order-functions/exercise.md +++ b/higher-order-functions/exercise.md @@ -15,21 +15,25 @@ Create a function called map that takes two inputs: Have `map` return a new array filled with numbers that are the result of using the 'callback' function on each element of the input array. ```js + map([1,2,3,4,5], multiplyByTwo); //-> [2,4,6,8,10] multiplyByTwo(1); //-> 2 multiplyByTwo(2); //-> 4 + ``` ## Challenge 4 The function `forEach` takes an array and a callback, and runs the callback on each element of the array. `forEach` does not return anything. ```js + var alphabet = ''; var letters = ['a', 'b', 'c', 'd']; forEach(letters, function(char) { alphabet += char; }); console.log(alphabet); //prints 'abcd' + ``` ## Extension 1 @@ -40,9 +44,11 @@ In the first part of the extension, you're going to rebuild `map` as `mapWith`. The function reduce takes an array and reduces the elements to a single value. For example it can sum all the numbers, multiply them, or any operation that you can put into a function. ```js + var nums = [4, 1, 3]; var add = function(a, b) { return a + b; } reduce(nums, add, 0); //-> 8 + ``` Here's how it works. The function has an "accumulator value" which starts as the `initialValue` and accumulates the output of each loop. The array is iterated over, passing the accumulator and the next array element as arguments to the `callback`. The callback's return value becomes the new accumulator value. The next loop executes with this new accumulator value. In the example above, the accumulator begins at 0. `add(0,4)` is called. The accumulator's value is now 4. Then `add(4, 1)` to make it 5. Finally `add(5, 3)` brings it to 8, which is returned. diff --git a/practice/closure.md b/practice/closure.md index 97a1ea4..eba9954 100644 --- a/practice/closure.md +++ b/practice/closure.md @@ -3,6 +3,7 @@ 1. Write a function called `multiplyBy` that takes a `number` as an argument and returns a function. Returned function takes another `number` as an argument and returns the multiplication of both the numbers. ```js + // Your code goes here function multiplyBy(num1) { @@ -17,11 +18,13 @@ function multiplyBy(num1) { const double = multiplyBy(2); const final = double(15); // final should be 30 + ``` 2. Write a function called `fullName` that takes a string `firstName` as an argument and returns a function. Returned function takes another string `lastName` as an argument and returns full name. ```js + // Your code goes here function fullName(firstName) { @@ -35,11 +38,13 @@ function fullName(firstName) { const name = fullName("Will"); const final = name("Smith"); // final should be "Will Smith" + ``` 3. Write a function called `isInBetween` which takes two parameter `a` and `b` and returns a function. When you call the returned function with any number it returns `true` if the value is in between `a` and `b`. ```js + function isInBetween(a, b) { // your code goes here function check(num) { @@ -53,11 +58,13 @@ const isChild = isInBetween(10, 100); isChild(21); // true isChild(45); // true isChild(103); // false + ``` 4. Write a function call `letsWishThem` that take one parameter `string` called `greeting` and returns a fucntion that takes another argument called `message`. ```js + function letsWishThem(greeting) { // your code goes here function constructMessage(message) { @@ -72,13 +79,21 @@ const callWithHey = letsWishThem("Hey"); const callWithHello = letsWishThem("Hello"); callWithHey("Arya"); // Hey Arya callWithHello("How Are You?"); // Hello How Are You? + ``` 5. Write a function called `addGame` which takes a string (name of the game) and returns a function calling that will increment the score by one and print something like `Score of Basketball is 1`. ```js + function addGame(gameName) { // your code goes here + let score = 0; + function inc(score) { + score++; + return `Your score of ${gameName} is ${score}`; + } + return inc; } // Output @@ -88,6 +103,7 @@ hockey(); // Your score of Hockey is 2 const cricket = addGame("Cricket"); cricket(); // Your score of Cricket is 2 cricket(); // Your score of Cricket is 2 + ``` 6. Write a function called `getCard` which takes one of these options (club, spade, heart, dimond) returns a function calling that function returns random card (2,3,4,5,6,7,8,9,10,J, Q, K, A) of that suit. @@ -110,4 +126,5 @@ randomClub(); // Card is: A Club const randomSpade = addGame("Spade"); randomSpade(); // Card is: 6 Spade randomSpade(); // Card is: A Spade + ``` diff --git a/practice/scope.md b/practice/scope.md index ad1f3c1..df1baec 100644 --- a/practice/scope.md +++ b/practice/scope.md @@ -70,7 +70,8 @@ fucntion addOne(num){ var two = addOne(1); console.log(two); -// Output : +// Output : 1 +// 2 ``` 6. Make a Execution Context Diagram for the following JS and write the output. @@ -82,6 +83,9 @@ const addOne = num => { }; var two = addOne(1); console.log(two); + +// Output: addOne is not defined. +// 2 ``` 7. Make a Execution Context Diagram for the following JS and write the output. @@ -350,6 +354,7 @@ sample("First", "Second", "Third"); 26. Guess the output and the reason behind that. ```js + if (true) { const myFunc = function() { console.log(username, "Second"); @@ -365,11 +370,13 @@ if (true) { // "Second" // let does not initialize variable during declaration phase. As we can't use any uninitialized variable that's why it'll throw an error. + ``` 27. Guess the output and the reason behind that. ```js + function outer() { let movie = "Mad Max: Fury Road"; function inner() { @@ -383,11 +390,13 @@ outer(); // Output: "I love this movie called MAD MAX: FURY ROAD" // Because of closure it gets the value of movie. + ``` 28. Guess the output and the reason behind that. ```js + function outer() { let movie = "Mad Max: Fury Road"; function inner() { @@ -402,11 +411,13 @@ outer(); // Output: "I love this movie called Before Sunrise" // inner function will search its memory first. + ``` 29. Guess the output and the reason behind that. ```js + function outer() { let movie = "Mad Max: Fury Road"; function inner() { From cfaca9dfc64ed683515926f19be8b3cfb3d8c81b Mon Sep 17 00:00:00 2001 From: Sanjib Roy Date: Wed, 18 Mar 2020 00:13:53 +0530 Subject: [PATCH 3/4] Modify Code --- higher-order-functions/exercise.js | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/higher-order-functions/exercise.js b/higher-order-functions/exercise.js index 0ded5eb..6e3a0e1 100644 --- a/higher-order-functions/exercise.js +++ b/higher-order-functions/exercise.js @@ -97,18 +97,17 @@ console.log(reduce(array, add, 0)); //Extension 3 function intersection(arrays) { - let ans; - let arr = arrays.flat(); - ans = arr.reduce((acc, cv, index) => { - - if(arr.indexOf(cv,index+1)!= -1 && !acc.includes(cv)) { - acc.push(cv); - } - return acc; - }, []); - return ans; + let ans; + let arr = arrays.flat(); + ans = arr.reduce((acc, cv, index) => { + + if(arrays.every(el => el.includes(cv)) && !acc.includes(cv) ) { + acc.push(cv); + } + return acc; + }, []); + return ans; } - // console.log(intersection([5, 10, 15, 20], [15, 88, 1, 5, 7], [1, 10, 15, 5, 20])); // should log: [5, 15] From 9a1592bd9e28d029b75620b31290a1e3dfb79b7f Mon Sep 17 00:00:00 2001 From: Sanjib Roy Date: Thu, 19 Mar 2020 13:16:17 +0530 Subject: [PATCH 4/4] correct code --- higher-order-functions/exercise.js | 47 ++++++++++++++++-------------- 1 file changed, 25 insertions(+), 22 deletions(-) diff --git a/higher-order-functions/exercise.js b/higher-order-functions/exercise.js index 6e3a0e1..69885a6 100644 --- a/higher-order-functions/exercise.js +++ b/higher-order-functions/exercise.js @@ -126,37 +126,40 @@ function union(arrays) { return ans; } -// console.log(union([5, 10, 15], [15, 88, 1, 5, 7], [100, 15, 10, 1, 5])); // should log: [5, 10, 15, 88, 1, 7, 100] //Extension 5 + function objOfMatches(array1, array2, callback) { - let obj = callback(array1, array2); - return obj; + let obj = callback(array1, array2); + return obj; } - - function getObj(array1, array2) { - - let copyArray2 = array2.map(el => el.toUpperCase()); + +function getObj(array1, array2) { + + + return array1.reduce( (acc, cv) => { + + for(let i = 0; i < array2.length; i++) { - return array1.reduce( (acc, cv) => { - let pos = copyArray2.indexOf(cv.toUpperCase()); - - if(pos !== -1 && !Object.keys(acc).includes(cv)) { - acc[cv] = array2[pos]; + if(cv.toUpperCase() == array2[i]) { + acc[cv] = array2[i]; + break; } - - return acc; - },{}); - } - - - let array1 = ['hi', 'howdy', 'bye', 'later', 'hello']; - let array2 = ['HI', 'Howdy', 'BYE', 'LATER', 'hello']; - - console.log(objOfMatches(array1, array2, getObj)); + } + + return acc; + },{}); + +} + +let array1 = ['hi', 'howdy', 'bye', 'later', 'hello']; +let array2 = ['HI', 'Howdy', 'BYE', 'LATER', 'hello']; + +console.log(objOfMatches(array1, array2, getObj)); + // console.log(objOfMatches(['hi', 'howdy', 'bye', 'later', 'hello'], ['HI', 'Howdy', 'BYE', 'LATER', 'hello'], function(str) { return str.toUpperCase(); })); // should log: { hi: 'HI', bye: 'BYE', later: 'LATER' }