diff --git a/paperproblems/HOF/problem1.txt b/paperproblems/HOF/problem1.txt index 5985535..b06818c 100644 --- a/paperproblems/HOF/problem1.txt +++ b/paperproblems/HOF/problem1.txt @@ -2,11 +2,28 @@ Someone has given you a function called filter You don't know what it does, but there are clues at the bottom of this file Use these clues to describe what filter is. Specifically: - - How many parameters does it have - - What are the types of the parameters - - What does it do? +****************************************< ANSWER >********************************************** + + - How many parameters does it have? + * 2 + + - What are the types of the parameters? + * 1st argument is an array (...technically an 'object', but whatever. :D) + * 2nd argument is a function; + + - What does it do? + 1) First, we see that in all cases: it returns an array. + 2) It iterates through each element in the array passed as the first argument, and + 3) checks, via the function passed as the second argument, whether the current element + evaluates to true or false in the conditional statements (if/else) executed within + the passed function... + a) If the expression evaluates to true: filter pushes the current element + in the resulting array (presented in step 1); + b) If the expression evaluates to false: the element is not pushed to the resulting array. + 4) The result, therefore, is an array of elements that passed the conditional tests as true. +************************************************************************************* var evenNumbers = [2, 4, 6, 8, 10]; var oddNumbers = [3, 5, 7, 9]; diff --git a/paperproblems/HOF/problem2.txt b/paperproblems/HOF/problem2.txt index 7215f54..133a428 100644 --- a/paperproblems/HOF/problem2.txt +++ b/paperproblems/HOF/problem2.txt @@ -2,9 +2,27 @@ Someone has given you a function called map You don't know what it does, but there are clues at the bottom of this file Use these clues to describe what map is. Specifically: - - How many parameters does it have - - What are the types of the parameters + +****************************************< ANSWER >********************************************** + + - How many parameters does it have? + * 2 + + - What are the types of the parameters? + * 1st argument is an array (...technically an 'object', but whatever. :D) + * 2nd argument is a function; + - What does it do? + 1) First, we see that in all cases: it returns an array. + 2) It iterates through each element in the array passed as the first argument, and + 3) performs, via the function passed as the second argument, an operation on the + current element, then pushes its result (the returned value) to the resulting + array (presented in step 1). + 4) The result, therefore, is an array of new elements that have been generated + based on operations performed on the array's elements (within arg1) in the passed + function (arg2). + +***************************************< /ANSWER >********************************************** var someNumbers = [1, 2, 3, 4]; var someStrings = ["bob", "ERIC"]; diff --git a/paperproblems/HOF/problem3.txt b/paperproblems/HOF/problem3.txt index 46f2ead..8b95eb5 100644 --- a/paperproblems/HOF/problem3.txt +++ b/paperproblems/HOF/problem3.txt @@ -8,4 +8,19 @@ function f(g) { return g(3,5); } -console.log(f(k)); \ No newline at end of file +console.log(f(k)); + +******************************************< ANSWER >******************************************** + +This will return an error, because the 2 arguments of k are never actually specified anywhere +(and certainly not by g...!) + +Specifically: +k would *not* take the result of g as parameters to be passed down to itself; +rather, function f calls function k in an attempt to evaluate parameters it could pass into/as +its argument g. However, function k is being called without any arguments -- and its arguments +are necessary to evaluate the returned value. +This program won't be able to add or multiply numbers to undefined arguments. +I expect this will output either a type error or NaN (honestly, I'm not sure which). + +************************************************************************************* \ No newline at end of file diff --git a/paperproblems/HOF/problem4.txt b/paperproblems/HOF/problem4.txt index 6441398..3bf4b98 100644 --- a/paperproblems/HOF/problem4.txt +++ b/paperproblems/HOF/problem4.txt @@ -12,4 +12,18 @@ function f(g, h) { return g(h, 1, 4); } -console.log(f(k, m)); \ No newline at end of file +console.log(f(k, m)); + +******************************************< ANSWER >******************************************** + +This will return an error, because the 3 arguments of k and the argument of m are never actually specified anywhere. + +Specifically: +f would *not* take the result of k as parameters to be passed down to itself; +rather, function f calls function k in an attempt to evaluate parameters it could pass into/as its argument g. However, function k is being called without any arguments -- and its arguments are necessary to evaluate the returned value. +Moreover, nothing is passed as an argument for m (as x). Double whammy. + +This program won't be able to add or multiply numbers to undefined arguments. +I expect this will output either a type error or NaN (honestly, I'm not sure which). + +************************************************************************************* \ No newline at end of file diff --git a/paperproblems/__proto__/problem1.txt b/paperproblems/__proto__/problem1.txt index fe263f1..b556341 100644 --- a/paperproblems/__proto__/problem1.txt +++ b/paperproblems/__proto__/problem1.txt @@ -1,10 +1,31 @@ -Draw the object diagram for this program +Draw the object diagram for this program var x1 = {}; var x2 = {}; var x3 = {}; var x4 = {}; -x2.__proto__ = x1; -x3.__proto__ = x2; -x4.__proto__ = x3; +x2.__proto__ = x1; // Impossible, would result in type error (cannot overwrite proto as a whole) +x3.__proto__ = x2; // Impossible, would result in type error (cannot overwrite proto as a whole) +x4.__proto__ = x3; // Impossible, would result in type error (cannot overwrite proto as a whole) +****************************************< ANSWER >********************************************** + + ╔════╤═══╗ + ║ │ ║ ┌────┬───┐ + ║ x1 │ ■───┤ {} │ ■────┐ + ║ │ ║ └────┴───┘ │ + ╟────┼───╢ │ + ║ │ ║ ┌────┬───┐ │ + ║ x2 │ ■───┤ {} │ ■────┤ + ║ │ ║ └────┴───┘ │ ┌───────────┬─────┐ + ╟────┼───╢ ├─►│ __proto__ │ ... │ + ║ │ ║ ┌────┬───┐ │ └───────────┴─────┘ + ║ x3 │ ■───┤ {} │ ■────┤ + ║ │ ║ └────┴───┘ │ + ╟────┼───╢ │ + ║ │ ║ ┌────┬───┐ │ + ║ x4 │ ■───┤ {} │ ■────┘ + ║ │ ║ └────┴───┘ + ╚════╧═══╝ + +************************************************************************************* \ No newline at end of file diff --git a/paperproblems/__proto__/problem2.txt b/paperproblems/__proto__/problem2.txt index 699ecd8..d396c2a 100644 --- a/paperproblems/__proto__/problem2.txt +++ b/paperproblems/__proto__/problem2.txt @@ -4,9 +4,11 @@ var x1 = {}; var x2 = {}; var x3 = {}; var x4 = {}; -x2.__proto__ = x1; -x3.__proto__ = x2; -x4.__proto__ = x3; +x2.__proto__ = x1; // Impossible, would result in type error (cannot overwrite proto as a whole) +x3.__proto__ = x2; // Impossible, would result in type error (cannot overwrite proto as a whole) +x4.__proto__ = x3; // Impossible, would result in type error (cannot overwrite proto as a whole) + +// Therefore... x1.age = 20; x3.age = 18; @@ -14,4 +16,16 @@ x3.age = 18; console.log(x1.age); console.log(x2.age); console.log(x3.age); -console.log(x4.age); \ No newline at end of file +console.log(x4.age); + +*************************************************< ANSWER >*************************************************** + +Technically, if you didn't remove the last three lines modifying __proto__ : you would get a type error. +...Once that was cleaned up; this is what we'd get: + +1st console.log: 20 +2nd console.log: 18 // None defined in object; last assigned key-value pair 'age' for __proto__ takes over. +3rd console.log: 18 +4th console.log: 18 // None defined in object; last assigned key-value pair 'age' for __proto__ takes over. + +*************************************************************************************************** \ No newline at end of file diff --git a/paperproblems/__proto__/problem3.txt b/paperproblems/__proto__/problem3.txt index aad4fcb..2bdcb15 100644 --- a/paperproblems/__proto__/problem3.txt +++ b/paperproblems/__proto__/problem3.txt @@ -11,4 +11,12 @@ You get the following exception: a) Explain what this exception means. -b) Why does this exception exist? What's wrong with a cyclic __proto__ value? \ No newline at end of file + * A __proto__ object would be generated and destroyed (overriden by an empty object, + which itself points to a __proto__ object...) over and over again, indefintely. + It is an endless loop and therefore cyclic. + Ergo: a creepy, ouroboric, self-cannibalistic mess that must be avoided at all costs. :) + +b) Why does this exception exist? What's wrong with a cyclic __proto__ value? + * This happens because we're trying to override the entirety of the __proto__ object, + which is a feature (implicit object) required to allow for Object-Oriented Programming in JavaScript. + An override would result in an infinite loop; because objects point to the __proto__ object when instantiated... \ No newline at end of file diff --git a/paperproblems/anonymous-functions/problem1.txt b/paperproblems/anonymous-functions/problem1.txt index 08e09e7..187f397 100644 --- a/paperproblems/anonymous-functions/problem1.txt +++ b/paperproblems/anonymous-functions/problem1.txt @@ -1,8 +1,15 @@ -Rewrite this program so that it doesn't have a single function definition -In other words, replace all the function definitions with anonymous functions - -function greet(x) { - console.log("hello " + x); -} - -greet(bob); \ No newline at end of file +Rewrite this program so that it doesn't have a single function definition +In other words, replace all the function definitions with anonymous functions + +********************************** + +const x = "Bob"; + +function greet() { + console.log("hello " + x); +} + +greet(); + +********************************* + diff --git a/paperproblems/anonymous-functions/problem2.txt b/paperproblems/anonymous-functions/problem2.txt index 7cfb344..69b7578 100644 --- a/paperproblems/anonymous-functions/problem2.txt +++ b/paperproblems/anonymous-functions/problem2.txt @@ -1,14 +1,5 @@ -Rewrite this program so that it doesn't have a single function definition -In other words, replace all the function definitions with anonymous functions -The final program should be on a single line - - -function greet(x) { - console.log("hello " + x); -} - -function call(f) { - f("bob"); -} - -call(greet); +Rewrite this program so that it doesn't have a single function definition +In other words, replace all the function definitions with anonymous functions +The final program should be on a single line + +const f = "bob", greet = () => console.log("hello " + f); \ No newline at end of file diff --git a/paperproblems/anonymous-functions/problem3.txt b/paperproblems/anonymous-functions/problem3.txt index 5d8a0fc..3a5f499 100644 --- a/paperproblems/anonymous-functions/problem3.txt +++ b/paperproblems/anonymous-functions/problem3.txt @@ -1,12 +1,9 @@ -Rewrite this program so that it doesn't have a single function definition -In other words, replace all the function definitions with anonymous functions - -function greet(x, y) { - console.log("hello " + x + " " + y); -} - -function call(f) { - f("Bob", "Dole"); -} - -call(greet); +Rewrite this program so that it doesn't have a single function definition +In other words, replace all the function definitions with anonymous functions + +const x = "Bob"; +const y = "Dole"; + +function greet() {console.log("hello " + x + " " + y)} + +greet(); \ No newline at end of file diff --git a/paperproblems/anonymous-functions/problem4.txt b/paperproblems/anonymous-functions/problem4.txt index 689d724..611fc5d 100644 --- a/paperproblems/anonymous-functions/problem4.txt +++ b/paperproblems/anonymous-functions/problem4.txt @@ -1,13 +1,4 @@ -Rewrite this program so that it doesn't have a single function definition -In other words, replace all the function definitions with anonymous functions - -function greet(x) { - console.log("hello " + x); -} - -function twice(f) { - f("bob"); - f("mary"); -} - -twice(greet); \ No newline at end of file +Rewrite this program so that it doesn't have a single function definition +In other words, replace all the function definitions with anonymous functions + +const f = "bob", greet = () => console.log("hello " + f); \ No newline at end of file diff --git a/paperproblems/anonymous-functions/problem5.txt b/paperproblems/anonymous-functions/problem5.txt index 2d69a4d..614ca49 100644 --- a/paperproblems/anonymous-functions/problem5.txt +++ b/paperproblems/anonymous-functions/problem5.txt @@ -1,19 +1,25 @@ -What is the output of this program? Don't cheat by running it! - -function askOnADate(n) { - if(n === "Bob") return "I do!"; - else return "Absolutely not!"; -} - -function soften(f) { - return function(name) { - var r = f(name); - if(r !== "I do!") return "maybe"; - else return r; - } - return ret; -} - -var softAskOnADate = soften(askOnADate); -console.log(softAskOnADate("Eric")); -console.log(softAskOnADate("Bob")); +What is the output of this program? Don't cheat by running it! + +********************************************************************* +"maybe" --- Softening applied for Eric (r !== "I do!") +"I do!" --- No softening is applied for Bob (r === "I do!") +ret is never actually used anywhere and could be removed altogether. +******************************************************************** + +function askOnADate(n) { + if(n === "Bob") return "I do!"; + else return "Absolutely not!"; +} + +function soften(f) { + return function(name) { + var r = f(name); + if(r !== "I do!") return "maybe"; + else return r; + } + return ret; +} + +var softAskOnADate = soften(askOnADate); +console.log(softAskOnADate("Eric")); +console.log(softAskOnADate("Bob")); \ No newline at end of file diff --git a/paperproblems/array-functions/problem1.txt b/paperproblems/array-functions/problem1.txt index 8e97911..5497301 100644 --- a/paperproblems/array-functions/problem1.txt +++ b/paperproblems/array-functions/problem1.txt @@ -1,16 +1,33 @@ -What is the output of this program? - -var animals = [ - {species: 'dog', name: 'Nacho'}, - {species: 'cat', name: 'Ramses'}, - {species: 'bunny',name: 'Flufftail'}, - {species: 'dog', name: 'Popcorn'}, - {species: 'giraffe', name: 'Neckbeard'}, - {species: 'possum', name: ''} -]; - -var dogs = animals.filter( - function(animal) - {return animal.species === 'dog';}); - +What is the output of this program? + +****************************************************** + +It will return 2. + +The animal array's filter function will look for animals +whoses value of species corresponds to the value of 'dog'; +since filter returns only items where the evaluation +expression returns true. + +The filter function *does* return a new array; so it *can* +be assigned to variable 'dogs'. + +dogs will contain an array containing 2 objects with 'dog' as +value of key 'species'. + +***************************************************** + +var animals = [ + {species: 'dog', name: 'Nacho'}, + {species: 'cat', name: 'Ramses'}, + {species: 'bunny',name: 'Flufftail'}, + {species: 'dog', name: 'Popcorn'}, + {species: 'giraffe', name: 'Neckbeard'}, + {species: 'possum', name: ''} +]; + +var dogs = animals.filter( + function(animal) + {return animal.species === 'dog';}); + console.log(dogs.length); \ No newline at end of file diff --git a/paperproblems/array-functions/problem2.txt b/paperproblems/array-functions/problem2.txt index e9050e5..2f1eb2d 100644 --- a/paperproblems/array-functions/problem2.txt +++ b/paperproblems/array-functions/problem2.txt @@ -1,16 +1,28 @@ -What is the output of this program? - -var animals = [ - {species: 'dog', name: 'Nacho'}, - {species: 'cat', name: 'Ramses'}, - {species: 'bunny',name: 'Flufftail'}, - {species: 'dog', name: 'Popcorn'}, - {species: 'giraffe', name: 'Neckbeard'}, - {species: 'possum', name: ''} -]; - -var letterN = animals.filter(function(animal) { - return animal.name !== undefined && animal.name[0] === 'N' -}); - +What is the output of this program? + +************************************************************************** + +"Nacho". +Because 'underneath', the filter function generates the new filtered array by +passing through each element of the original array. +The very first element that would return a value of true on the evaluation +expression is "Nacho"; hence, the name property of letterN at index position 0 +is "Nacho". + +************************************************************************* + + +var animals = [ + {species: 'dog', name: 'Nacho'}, + {species: 'cat', name: 'Ramses'}, + {species: 'bunny',name: 'Flufftail'}, + {species: 'dog', name: 'Popcorn'}, + {species: 'giraffe', name: 'Neckbeard'}, + {species: 'possum', name: ''} +]; + +var letterN = animals.filter(function(animal) { + return animal.name !== undefined && animal.name[0] === 'N' +}); + console.log(letterN[0].name); \ No newline at end of file diff --git a/paperproblems/array-functions/problem3.txt b/paperproblems/array-functions/problem3.txt index e1182ab..d58ca36 100644 --- a/paperproblems/array-functions/problem3.txt +++ b/paperproblems/array-functions/problem3.txt @@ -1,13 +1,30 @@ -var animals = [ - {species: 'dog', name: 'Nacho'}, - {species: 'cat', name: 'Ramses'}, - {species: 'bunny',name: 'Flufftail'}, - {species: 'dog', name: 'Popcorn'}, - {species: 'giraffe', name: 'Neckbeard'}, - {species: 'possum', name: ''} -]; - -var animalNames = animals.map( - function(animal) {return animal.name}); - +**************************<...ANSWER-TO-A-NONEXISTENT-QUESTION...>************************** + +"Nacho,Ramses,Flufftail,Popcorn,Neckbeard" + +When the join function isn't being passed a delimiter, it simply joins the elements of its +array with commas (no spaces after the commas). + +If the join function had been called with an empty string literal as its argument (''); +the name of all animals would have "chained" into a long string. +("NachoRamsesFlufftailPopcordNeckbeard") + +If the join function had been called with an space as its argument (' '); +the name of all animals would have "chained" into a long string with a space between +each name. ("Nacho Ramses Flufftail Popcord Neckbeard" + +*************************************************** + +var animals = [ + {species: 'dog', name: 'Nacho'}, + {species: 'cat', name: 'Ramses'}, + {species: 'bunny',name: 'Flufftail'}, + {species: 'dog', name: 'Popcorn'}, + {species: 'giraffe', name: 'Neckbeard'}, + {species: 'possum', name: ''} +]; + +var animalNames = animals.map( + function(animal) {return animal.name}); + console.log(animalNames.join()); \ No newline at end of file diff --git a/paperproblems/array-functions/problem4.txt b/paperproblems/array-functions/problem4.txt index 8b933aa..3f89b0f 100644 --- a/paperproblems/array-functions/problem4.txt +++ b/paperproblems/array-functions/problem4.txt @@ -1,18 +1,28 @@ -var animals = [ - {species: 'dog', name: 'Nacho'}, - {species: 'cat', name: 'Ramses'}, - {species: 'bunny',name: 'Flufftail'}, - {species: 'dog', name: 'Popcorn'}, - {species: 'giraffe', name: 'Neckbeard'}, - {species: 'possum', name: ''} -]; - -function isDog(animal) { - return animal.species === 'dog'; -} - -animals.some(isDog) -animals.every(isDog) - - - +**************************<...ANSWER-TO-A-NONEXISTENT-QUESTION...>************************** + +true: Because *some* (read: "at least one") elements of the array are a dog; +false: Because *not all* elements of the array are a dog. + +If we had run the .every(isDog) function on the filtered 'dogs' array created in problem #1, +it would have returned true. + +*************************************************** + +var animals = [ + {species: 'dog', name: 'Nacho'}, + {species: 'cat', name: 'Ramses'}, + {species: 'bunny',name: 'Flufftail'}, + {species: 'dog', name: 'Popcorn'}, + {species: 'giraffe', name: 'Neckbeard'}, + {species: 'possum', name: ''} +]; + +function isDog(animal) { + return animal.species === 'dog'; +} + +animals.some(isDog) +animals.every(isDog) + + + diff --git a/paperproblems/arrow-functions/problem1.txt b/paperproblems/arrow-functions/problem1.txt index 7338e61..a7f5ada 100644 --- a/paperproblems/arrow-functions/problem1.txt +++ b/paperproblems/arrow-functions/problem1.txt @@ -1,19 +1,37 @@ -For each of the following expressions: - - Does it have a syntax error? - - If it doesn't have a syntax error, what are the probable input and output types of the function? - -a) x => x + 1 - -b) x, y => x * y - -c) x => { x * 2 } - -d) (x, z) => {console.log(z); return x * z} - -e) x => console.log(z); return x * z - -f) (x) => x * 2 - -e) () => console.log("hello") - +For each of the following expressions: +1) Does it have a syntax error? +2) If it doesn't have a syntax error, what are the probable input and output types of the function? + +a) x => x + 1 + 1) No + 2) Input: number; + Output: returns a number (number not logged). + +b) x, y => x * y + 1) Syntax error: 2 arguments not enclosed in parentheses. + 2) N/A + +c) x => { x * 2 } + 1) Syntax error: no return keyword after the first curly brace; so no value returned. + 2) N/A + +d) (x, z) => {console.log(z); return x * z} + 1) No + 2) input: numbers + output: number (2nd argument) logged & number returned (both args operated on). + +e) x => console.log(z); return x * z + 1) Syntax error: no z argument passed to arrow function (assuming z is not defined at a higher level). + 2) N/A + +f) (x) => x * 2 + 1) No (although parentheses are not necessary for a single argument.) + 2) input : number + output : returns a number (number not logged). + +e) () => console.log("hello") + 1) No + 2) input: undefined; + output: "hello" logged, but returns undefined. + When you're done, check all your answers in the developer console. \ No newline at end of file diff --git a/paperproblems/bind/problem1.txt b/paperproblems/bind/problem1.txt index e57fc23..f67b3b4 100644 --- a/paperproblems/bind/problem1.txt +++ b/paperproblems/bind/problem1.txt @@ -1,12 +1,18 @@ -What is the output of this program? - -'use strict'; - -var obj = { - bar: function() {console.log(this.baz);}, - baz: 12 -} - -obj.bar = obj.bar.bind({baz: 4}); - +What is the output of this program? + +********************************************************************************************************************* +Answer: 4 +However: this does not imply that it overwrote the 'baz' property of the original declared object. +Rather: a new object was created; and the 'bar' property of the original object pointed to the new object's value for 'baz'. +******************************************************************************************************************** + +'use strict'; + +var obj = { + bar: function() {console.log(this.baz);}, + baz: 12 +} + +obj.bar = obj.bar.bind({baz: 4}); + obj.bar(); \ No newline at end of file diff --git a/paperproblems/bind/problem2.txt b/paperproblems/bind/problem2.txt index 6c9d16d..6931185 100644 --- a/paperproblems/bind/problem2.txt +++ b/paperproblems/bind/problem2.txt @@ -1,18 +1,21 @@ -What is the output of this program? - -'use strict'; - -var bob = { - name: "Bob", - introduction: function() {console.log("Hi I'm " + this.name);} -} - -var eric = { name: "Eric" }; - -bob.introduction = bob.introduction.bind(bob); - -eric.introduction = bob.introduction; - -eric.introduction = eric.introduction.bind({name: "Steve"}); - +What is the output of this program? + +*********************************************************************************************************** +Answer: "Hi I'm Bob" +The eric object was given the 'introduction' property through bob.introduction (line 8); +which itself was already bound to bob at the point this property assignment took place. +Because the property was created as such (and not paired with its own function from the start, for example): +the binding remained linked to bob; since the binding is permanent and cannot have its target reassigned. +********************************************************************************************************** + +'use strict'; + +var bob = { + name: "Bob", + introduction: function() {console.log("Hi I'm " + this.name);} +} +var eric = { name: "Eric" }; +bob.introduction = bob.introduction.bind(bob); +eric.introduction = bob.introduction; +eric.introduction = eric.introduction.bind({name: "Steve"}); eric.introduction(); \ No newline at end of file diff --git a/paperproblems/callbacks/problem1.txt b/paperproblems/callbacks/problem1.txt index 63df256..1bf60ca 100644 --- a/paperproblems/callbacks/problem1.txt +++ b/paperproblems/callbacks/problem1.txt @@ -1,15 +1,31 @@ -What does the following program do? - -function g() { - console.log("Hello!") -} - -function f() { - setTimeout(g, 500); -} - -function h() { - setTimeout(f, 1000); -} - +What does the following program do? + +****************************************************************************** + +#1) It will first evaluate the "last" setTimeout; then function h, then function f, and +finally function g (which, in itself, is a process that takes up a little time.) + +#2) Once the evaluation is complete: the "countdown" will actually start. +It will run the "last" setTimeout and wait 0.2 seconds before executing function h. +In turn, the setTimeout of h will then wait 1 second before executing function f. +In turn, the setTimeout of f will then wait 0.5 second before executing function g. +Only at that point will the console log "Hello!" + +So, the absolute minimum amount of time this would take is 1.7 seconds; but it likely +will take a little more time due to the evaluation process (#1). + +***************************************************************************** + +function g() { + console.log("Hello!") +} + +function f() { + setTimeout(g, 500); +} + +function h() { + setTimeout(f, 1000); +} + setTimeout(h, 200); \ No newline at end of file diff --git a/paperproblems/callbacks/problem2.txt b/paperproblems/callbacks/problem2.txt index 1ee06dd..5a7da4e 100644 --- a/paperproblems/callbacks/problem2.txt +++ b/paperproblems/callbacks/problem2.txt @@ -1,11 +1,19 @@ -What does the following program do? - -function g() { - console.log("Hello!") -} - -function h() { - setInterval(g, 1000); -} - +What does the following program do? + +****************************************************************************** + +It won't log anything before 2 seconds or so; but then it will log "Hello!" to the +console twice as much as it did in the previous second, until it is logged as often as +the machine can possibly handle... which sounds like a very bad idea. :) + +***************************************************************************** + +function g() { + console.log("Hello!") +} + +function h() { + setInterval(g, 1000); +} + setInterval(h, 1000); \ No newline at end of file diff --git a/paperproblems/classes/problem1.txt b/paperproblems/classes/problem1.txt index 9fbc41e..226046a 100644 --- a/paperproblems/classes/problem1.txt +++ b/paperproblems/classes/problem1.txt @@ -1,14 +1,38 @@ -Draw the object diagram for the following program. - -class Dog { - constructor(breed, age, gender) { - this.breed = breed; - this.age = age; - this.gender = gender; - } - bark() { - console.log("Woof."); - } -} - -var someDog = new Dog("schnitzel", 2, "male"); +Draw the object diagram for the following program. + +************************************************************************** + +1) In the 'Global Variables' box: + - Dog (class) + - someDog (object) + +2) Dog points to a class. + Class contains: + - prototype (own; used for receiving the link from someDog.__proto__) + - bark: Link to a function (A). + - __proto__: Link to Global (Empty) Object. + +3) someDog points to a dog object containing the following properties: + > breed: "schnitzel" + > age: 2 + > gender: "male" + > __proto__: Link to Dog.prototype + +4) Function (A/'bark'). + Contains: + - __proto__: Link to Global (Empty) Object. + +************************************************************************* + +class Dog { + constructor(breed, age, gender) { + this.breed = breed; + this.age = age; + this.gender = gender; + } + bark() { + console.log("Woof."); + } +} + +var someDog = new Dog("schnitzel", 2, "male"); diff --git a/paperproblems/classes/problem2.txt b/paperproblems/classes/problem2.txt index 60891b1..8fa23fc 100644 --- a/paperproblems/classes/problem2.txt +++ b/paperproblems/classes/problem2.txt @@ -1,22 +1,31 @@ -What is the output of this program? - -class Person { - constructor(age, name, salary) { - this.age = age; - this.name = name; - this.salary = salary; - } - increaseSalary(amount) { - console.log("Yay!"); - this.salary = this.salary + amount; - } - toString() { - return "My name is " + this.name + - "and I'm " + this.age + " and I make " + this.salary; - } -} - -var bob = new Person(25, "Bob", 40000); - -bob.increaseSalary(-500); +What is the output of this program? + +**************************************************************************** + +bob.increaseSalary: logs "Yay!" // Even though we're actually reducing his salary. + +bob.toString: returns "My name is Bob and I'm 25 and I make 39500", which is -then- +logged by the wrapping 'console.log()'. + +*************************************************************************** + +class Person { + constructor(age, name, salary) { + this.age = age; + this.name = name; + this.salary = salary; + } + increaseSalary(amount) { + console.log("Yay!"); + this.salary = this.salary + amount; + } + toString() { + return "My name is " + this.name + + "and I'm " + this.age + " and I make " + this.salary; + } +} + +var bob = new Person(25, "Bob", 40000); + +bob.increaseSalary(-500); console.log(bob.toString()); \ No newline at end of file diff --git a/paperproblems/conditional-operator/problem1.txt b/paperproblems/conditional-operator/problem1.txt index fabd9e8..83da551 100644 --- a/paperproblems/conditional-operator/problem1.txt +++ b/paperproblems/conditional-operator/problem1.txt @@ -1,7 +1,24 @@ -What does this program output? - -function f(x) { - return x < 5 ? 3 : x > 8 ? 4 : x == 6 ? 12 : 9; -} - +What does this program output? + +******************************************************************************************************** + +This will return 9. + +1st conditional test: 5 is not smaller than 5 (false); so, moving onto the next ":" for further instructions... +2nd conditional test: 5 is not greater than 8 (false); so, moving onto the next ":" for further instructions... +3rd conditional test: 5 is not equal to 6 (false); so, moving onto the next ":", which returns 9. + +******************************************************************************************************* + + +function f(x) { + return x < 5 + ? 3 + : x > 8 + ? 4 + : x == 6 + ? 12 + : 9; +} + console.log(f(5)); \ No newline at end of file diff --git a/paperproblems/constructor-functions/problem1.txt b/paperproblems/constructor-functions/problem1.txt index bd77a77..e431113 100644 --- a/paperproblems/constructor-functions/problem1.txt +++ b/paperproblems/constructor-functions/problem1.txt @@ -1,15 +1,36 @@ -Draw the object diagram for the following program. -Hints: - - There are two variables: makePerson and bob - - makePerson has a property called prototype - - bob has properties constructor and __proto__ - -function Person(name, age) { - this.name = name; - this.age = age; - this.greet = function() { - console.log("Hello my name is " + this.name); - } -} - +Draw the object diagram for the following program. + +****************************************************************************** + +Variables in 'Global' box: + 1> Person + 2> bob + (3> __proto__) + +1> Link from Person pointing to a function with a prototype [A]. (Constructor function) + +2> Link from Bob pointing to an object with the following properties: + - name: "Bob" + - age: 30 + - greet: Link from greet to a function with a prototype [B]. (Greeting Message) + - constructor: Link from constructor to function labeled [A] above. + - __proto__: Link from __proto__ to function labeled [A] above. + +(3> Link from __proto__ to Object.prototype [C]. [Global Object Prototype]) + +***************************************************************************** + +Hints: + - There are two variables: makePerson and bob + - makePerson has a property called prototype + - bob has properties constructor and __proto__ + +function Person(name, age) { + this.name = name; + this.age = age; + this.greet = function() { + console.log("Hello my name is " + this.name); + } +} + var bob = new Person("Bob", 30); \ No newline at end of file diff --git a/paperproblems/constructor-functions/problem2.txt b/paperproblems/constructor-functions/problem2.txt index 4cb7dd9..f21f789 100644 --- a/paperproblems/constructor-functions/problem2.txt +++ b/paperproblems/constructor-functions/problem2.txt @@ -1,15 +1,24 @@ -What does this program output? - -function Person(name, age) { - this.name = name; - this.age = age; - this.greet = function() { - console.log("Hello my name is " + this.name); - } -} - -var bob = new Person("Bob", 30); - -Person.prototype.leave = function() {return this.name + " is leaving";} - +What does this program output? + +*********************************************************************************** + +It should output "Bob is leaving", because bob was built on the Person prototype and the +Person prototype was updated to contain the new key "leave"; which is a function (much +like "greet") that has been called at the very last line of the program. +In that context, "this" refers to the calling object "bob"; so all works as intended here. + +********************************************************************************** + +function Person(name, age) { + this.name = name; + this.age = age; + this.greet = function() { + console.log("Hello my name is " + this.name); + } +} + +var bob = new Person("Bob", 30); + +Person.prototype.leave = function() {return this.name + " is leaving";} + bob.leave(); \ No newline at end of file diff --git a/paperproblems/constructor-functions/problem3.txt b/paperproblems/constructor-functions/problem3.txt index 2c875ee..99f9448 100644 --- a/paperproblems/constructor-functions/problem3.txt +++ b/paperproblems/constructor-functions/problem3.txt @@ -1,19 +1,100 @@ -What does this program output? - -function Person(name, age) { - this.name = name; - this.age = age; - this.greet = function() { - console.log("Hello my name is " + this.name); - } -} - -var bob = new Person("Bob", 30); - -bob.constructor.prototype.salary = 40000; -bob.__proto__.salary = bob.__proto__.salary + 100; -Person.prototype.salary = Person.prototype.salary + 300; -Person.__proto__.salary = Person.__proto__.salary + 400; -bob.salary = bob.salary + 50; - +What does this program output? + +*********************************************************************************** + +It should output 40450. + +The key point here is that "prototype" should be used to access/create/modify an object's +own prototypal properties; whereas "__proto__" should be used in the context of an +instantiated object (e.g.: in this case, the "bob" object [sic]) to access its parent's +properties. + +In other words: "__proto__" refers to prototype properties found "one level up" (those of +the parent), and "prototype", to an object's own level/properties. + +This would allow us to infer the following: + +A) bob.constructor.prototype.salary = 40000 // This operation works because we're calling + "prototype" on bob's "Person" constructor; + so this syntax is valid, and the property is + created in the constructor's prototype. + It's a more "convoluted" way of writing + "Person.prototype.salary = ..." or + "bob.__proto__.salary"; only, we're using + an instantiated Person object to set a new + property to its constructor. + And because bob's an instantiated object + of Person, that property is accessible to + him as well (though not as one of *his* own + object properties.) + +B) bob.__proto__.salary = bob.__proto__.salary + 100 // Here, this operation also works on + bob's prototype (ergo: the Person + constructor); but because we are + updating that property through the + instantiated "bob" opbject; we had + to use __proto__ (not "prototype"). + We are therefore now at 40100 for + the Person prototype's salary... + and bob's! + +C) Person.prototype.salary = Person.prototype.salary + 300 // Same result as the above, + except that we are updating + the Person prototype's + "salary" property through + the Person constructor; + we therefore had to use the + keyword "prototype" here + (not __proto__), since we're + not doing so through an + instantiated Person object. + +D) Person.__proto__.salary = Person.__proto__.salary + 400 // This does NOTHING USEFUL in + *this* particular context. + there's no existing "salary" + property for the __proto__ of + Person (which is in fact an + instantiation of the "global + Object"), so this operation + does not return a number + (undefined + 400 = NaN), and + especially does NOT update + the appropriate (existing) + property value we've been + modifying thus far (in + Person's *own* prototype). + The value of the Person + prototype's salary is still, + therefore, 40400 (not 40800). + +E) bob.salary = bob.salary + 50 // Here, we're in fact doing two things: + 1. The left-hand part of this operation sets a "salary" + property to bob's own properties (since it must be + noted that bob was getting this property from its + constructor's prototype all along); + 2. The right-hand side of the operation actually + assigns, to property "bob.salary", the value of the + Person prototype's current "salary" value, + 50. + the value of "bob.salary" is therefore no longer a + pointer, but a primitive type: the number 40450. + +********************************************************************************** + + +function Person(name, age) { + this.name = name; + this.age = age; + this.greet = function() { + console.log("Hello my name is " + this.name); + } +} + +var bob = new Person("Bob", 30); + +bob.constructor.prototype.salary = 40000; // The constructor being function "Person"... +bob.__proto__.salary = bob.__proto__.salary + 100; // Now 40100 -- both for Bob and the Person prototype +Person.prototype.salary = Person.prototype.salary + 300; // Now 40400 -- both for Bob and the Person prototype +Person.__proto__.salary = Person.__proto__.salary + 400; // Still 40400 -- both for Bob and the Person prototype +bob.salary = bob.salary + 50; // Now 40450 for Bob, through his own new salary property, and 40400 for the Person prototype. + console.log(bob.salary); \ No newline at end of file diff --git a/paperproblems/constructor-functions/problem4.txt b/paperproblems/constructor-functions/problem4.txt index 10d57df..7800d12 100644 --- a/paperproblems/constructor-functions/problem4.txt +++ b/paperproblems/constructor-functions/problem4.txt @@ -1,15 +1,27 @@ -What does this program output? - -function Person(name, age) { - this.name = name; - this.age = age; - this.greet = function() { - console.log("Hello my name is " + this.name); - } -} - -var bob = Person("Bob", 30); - -bob.name = bob.name + " Dole"; - +What does this program output? + +************************************************************************************ +This results in an error, because variable "bob" actually references the Person function +and not a new instantiation of Person (a new "Person" object for "Bob"). + +We can't add a string to a function; so this results in a type error. + +We could fix this program by adding the keyword "new" between "=" and "Person": +var bob = new Person("Bob", 30); + +This would give us a properly instantiated 'Person' object to access/modify as we please. +*********************************************************************************** + +function Person(name, age) { + this.name = name; + this.age = age; + this.greet = function() { + console.log("Hello my name is " + this.name); + } +} + +var bob = Person("Bob", 30); + +bob.name = bob.name + " Dole"; + bob.greet(); \ No newline at end of file diff --git a/paperproblems/constructor-functions/problem5.txt b/paperproblems/constructor-functions/problem5.txt index 70770f4..3808252 100644 --- a/paperproblems/constructor-functions/problem5.txt +++ b/paperproblems/constructor-functions/problem5.txt @@ -1,14 +1,24 @@ -Rewrite this program so that it does't use the new keyword. -The program must be equivalent in every other way. -(You would never do this in production. This is for learning purposes) - -function Person(name, age) { - this.name = name; - this.age = age; - this.greet = function() { - console.log("Hello my name is " + this.name); - } -} - -var bob = new Person("Bob", 30); -var sue = new Person("Sue", 24); +Rewrite this program so that it does't use the new keyword. +The program must be equivalent in every other way. + +**************************************************************************************** +function Person(name, age) { return {"name": name, "age": age, "__proto__": Person.prototype } } +var bob = Person("Bob", 30); +// Person.gender = "Male"; +// console.log(bob.gender) === "Male"; so the __proto__ works as expected. +*************************************************************************************** + +var personPrototype = {} +function Person(name, age) { + var ret = { + "name": name, + "age": age, + greet: () => { + console.log("Hello my name is " + this.name); + } + } + ret.__proto__ = Person.prototype; + return ret; +} + +var bob = Person("Bob", 30); \ No newline at end of file diff --git a/paperproblems/exceptions/problem1.txt b/paperproblems/exceptions/problem1.txt index b39b619..407ab10 100644 --- a/paperproblems/exceptions/problem1.txt +++ b/paperproblems/exceptions/problem1.txt @@ -13,3 +13,5 @@ function g() { } g(); + +**************************************** ANSWER : 500 \ No newline at end of file diff --git a/paperproblems/exceptions/problem2.txt b/paperproblems/exceptions/problem2.txt index 1108a2c..aea3e90 100644 --- a/paperproblems/exceptions/problem2.txt +++ b/paperproblems/exceptions/problem2.txt @@ -23,3 +23,6 @@ function g() { } g(); + +**************************************** ANSWER : 500 (caught in h()) + "some error" (caught in g()) \ No newline at end of file diff --git a/paperproblems/inheritance/problem1.txt b/paperproblems/inheritance/problem1.txt index 3de989f..9e1d3f1 100644 --- a/paperproblems/inheritance/problem1.txt +++ b/paperproblems/inheritance/problem1.txt @@ -1,27 +1,40 @@ -What does the following problem output? - -class Shape { - constructor(shapeName) { - this.shapeName = shapeName; - } - toString() { - return this.shapeName + " with area " + - this.area() + " and perimeter " + this.perimeter(); - } -} - -class Square extends Shape { - constructor(size) { - super("square"); - this.size = size; - } - area() { - return this.size * this.size; - } - perimeter() { - return this.size * 4; - } -} - -var s = new Square(5); +What does the following problem output? + +********************************************************************************** + +s.toString() returns... +"square with area 25 and perimeter 20" +...which is then logged by the wrapping console.log() (outputs the same as the return). + +Even though "area" and "perimeter" aren't inherent properties of the Shape class or its +constructor, Shape can still call on "this.area()" and "this.perimeter()" successfully +because it has been extended by the Square class; so it's able to call on data from +that subclass. + +********************************************************************************* + +class Shape { + constructor(shapeName) { + this.shapeName = shapeName; + } + toString() { + return this.shapeName + " with area " + + this.area() + " and perimeter " + this.perimeter(); + } +} + +class Square extends Shape { + constructor(size) { + super("square"); + this.size = size; + } + area() { + return this.size * this.size; + } + perimeter() { + return this.size * 4; + } +} + +var s = new Square(5); console.log(s.toString()); \ No newline at end of file diff --git a/paperproblems/inheritance/problem2.txt b/paperproblems/inheritance/problem2.txt index f9d6898..d641d90 100644 --- a/paperproblems/inheritance/problem2.txt +++ b/paperproblems/inheritance/problem2.txt @@ -1,13 +1,30 @@ -Define a Rectangle class that extends the Shape class -Then create an instance of the Rectangle class -Then call the toString method on the new instance and print it out - -class Shape { - constructor(shapeName) { - this.shapeName = shapeName; - } - toString() { - return this.shapeName + " with area " + - this.area() + " and perimeter " + this.perimeter(); - } -} +Define a Rectangle class that extends the Shape class +Then create an instance of the Rectangle class +Then call the toString method on the new instance and print it out + +************************************************************************** + +class Shape { + constructor(shapeName) { + this.shapeName = shapeName; + } + toString() { + return this.shapeName + " with area " + + this.area() + " and perimeter " + this.perimeter(); + } +} + +class Rectangle extends Shape { + constructor(width, height) { + super("Rectangle"); + this.width = width, + this.height = height + } + area() { return this.width * this.height } + perimeter() { return (this.width + this.height) * 2 } +} + +tangledWreck = new Rectangle(6, 4); +console.log(tangledWreck.toString()); + +************************************************************************* \ No newline at end of file diff --git a/paperproblems/return/problem1.txt b/paperproblems/return/problem1.txt index fed99b8..f973d7c 100644 --- a/paperproblems/return/problem1.txt +++ b/paperproblems/return/problem1.txt @@ -7,3 +7,5 @@ function f() { console.log(f()); +**************************************** ANSWER : 5 + diff --git a/paperproblems/this/problem1.txt b/paperproblems/this/problem1.txt index 7212ac6..5922b8b 100644 --- a/paperproblems/this/problem1.txt +++ b/paperproblems/this/problem1.txt @@ -1,11 +1,18 @@ -What is the output of this program? - -'use strict'; - -function foo() { - console.log(this.baz); -} - -var obj = {bar: foo, baz: 8}; -obj.bar(); - +What is the output of this program? + +******************* +8 +In this context, baz refers +to a property (.) of this; +and not the window object. +****************** + +'use strict'; + +function foo() { + console.log(this.baz); +} + +var obj = {bar: foo, baz: 8}; +obj.bar(); + diff --git a/paperproblems/this/problem2.txt b/paperproblems/this/problem2.txt index 1144503..588bb2d 100644 --- a/paperproblems/this/problem2.txt +++ b/paperproblems/this/problem2.txt @@ -1,12 +1,29 @@ -What is the output of this program? - -'use strict'; - -var obj = { - bar: function() {console.log(this.baz);}, - baz: 12 -} - -var g = obj.bar; -g(); - +What is the output of this program? + +************************************************** +Undefined. + +With this syntax: the context of 'this' is that of the +window object and not that of the object; because we're +actually calling function g(), and not the original +content of 'obj.bar'). +In order for this to work as intended, bar should have +been A) called as a function (()) from within the variable +declaration (e.g.: var g = obj.bar()); and B) triggered by +calling only g; and not g(). + + var g = obj.bar(); + g; + +************************************************* + +'use strict'; + +var obj = { + bar: function() {console.log(this.baz);}, + baz: 12 +} + +var g = obj.bar; +g(); + diff --git a/paperproblems/this/problem3.txt b/paperproblems/this/problem3.txt index dcfda4d..b12a5ce 100644 --- a/paperproblems/this/problem3.txt +++ b/paperproblems/this/problem3.txt @@ -1,17 +1,27 @@ -What is the output of this program? - -'use strict'; - -var obj = { - bar: function() {console.log(this.baz);}, - baz: 12 -} - -var obj2 = { - bar: function() {console.log(this.baz + 2);}, - baz: 12 -} - -obj2.bar = obj.bar; -obj2.bar(); - +What is the output of this program? + +***************************************** +12. +However, it isn't the value of the baz property +for obj (the one that's being pointed to via +obj2.bar); it's the value of baz from obj2. +The pointer only changes the pointer of bar; but +its parent context is still that of the object +that calls it, which is obj2. +**************************************** + +'use strict'; + +var obj = { + bar: function() {console.log(this.baz);}, + baz: 12 +} + +var obj2 = { + bar: function() {console.log(this.baz + 2);}, + baz: 12 +} + +obj2.bar = obj.bar; +obj2.bar(); + diff --git a/paperproblems/this/problem4.txt b/paperproblems/this/problem4.txt index d7a9ebd..ddc8de0 100644 --- a/paperproblems/this/problem4.txt +++ b/paperproblems/this/problem4.txt @@ -1,14 +1,23 @@ -What is the output of this program? - -'use strict'; - -var obj = { - bar: function(i) {console.log(this.baz + i);}, - baz: 12 -} - -function f(g) { - console.log(g(4)); -} - +What is the output of this program? + +*********************************************** +It's an error. +The context of "this" is that of a function (g(4)) and +not that of an object. In strict mode; it's impossible +to add the value of i (a number) to something that +returns undefined (since it isn't an object that's in +context here). +********************************************** + +'use strict'; + +var obj = { + bar: function(i) {console.log(this.baz + i);}, + baz: 12 +} + +function f(g) { + console.log(g(4)); +} + f(obj.bar); \ No newline at end of file diff --git a/paperproblems/variable-scoping/problem1.txt b/paperproblems/variable-scoping/problem1.txt index 281bdd6..ce5745d 100644 --- a/paperproblems/variable-scoping/problem1.txt +++ b/paperproblems/variable-scoping/problem1.txt @@ -1,11 +1,25 @@ -What is the output of this program? - -var x = 1; - -function f() { - x = x * 2; - console.log(x); -} - -f(); -f(); +What is the output of this program? + +******************** +first call of f(): 2 + (Returns: undefined) + +second call of f(): 4 + (Returns: undefined) + +Why? +Variable x is a closure +of function f. (Declared in +global scope; therefore +increments at every call.) +******************* + +var x = 1; + +function f() { + x = x * 2; + console.log(x); +} + +f(); +f(); diff --git a/paperproblems/variable-scoping/problem2.txt b/paperproblems/variable-scoping/problem2.txt index eb70c9d..b538504 100644 --- a/paperproblems/variable-scoping/problem2.txt +++ b/paperproblems/variable-scoping/problem2.txt @@ -1,10 +1,26 @@ -What is the output of this program? - -function f() { - var x = 1; - x = x * 2; - console.log(x); -} - -f(); +What is the output of this program? + +******************** +first call of f(): 2 + (Returns: undefined) + +second call of f(): 2 + (Returns: undefined) + +Why? +Variable x is not a closure +of function f; it is +declared every time the +function runs and therefore, +the result is the same at +every call. +******************* + +function f() { + var x = 1; + x = x * 2; + console.log(x); +} + +f(); f(); \ No newline at end of file diff --git a/paperproblems/variable-scoping/problem3.txt b/paperproblems/variable-scoping/problem3.txt index ba8ada5..ac5b75f 100644 --- a/paperproblems/variable-scoping/problem3.txt +++ b/paperproblems/variable-scoping/problem3.txt @@ -1,14 +1,41 @@ -What is the output of this program? - -var x = 1; -var y = 3; - -function f() { - var y = 5; - x = x * 2; - console.log(x + y); -} - -f(); -f(); +What is the output of this program? + +************************************************** +first call of f(): 7 + (Returns: undefined) + +second call of f(): 9 + (Returns: undefined) + +final console.log(): 3 + +Why? + +@ first call: global y is shadowed by local y because +y is re-declared locally. The global x is still being +accessed and modified, though. +x is now 2 across the board; making x (2) + y (5) === 7. + +@ second call: global y is shadowed by local y because +y is re-declared locally. The global x (which changed +from 1 to 2 by the previous call of function f) is still +being accessed and modified, though. +x is now 4 across the board; making x (4) + y (5) === 9. + +@console.log(): The program cannot access the value of y +within the function; hence, it will return the value of +the 'global' y, which is still 3. +************************************************* + +var x = 1; +var y = 3; + +function f() { + var y = 5; + x = x * 2; + console.log(x + y); +} + +f(); +f(); console.log(y); \ No newline at end of file diff --git a/paperproblems/variable-scoping/problem4.txt b/paperproblems/variable-scoping/problem4.txt index 2294b2e..47494df 100644 --- a/paperproblems/variable-scoping/problem4.txt +++ b/paperproblems/variable-scoping/problem4.txt @@ -1,17 +1,21 @@ -Which variables are in scope on the indicated line? - -var x = 5; -function f() { - var y = 8; - function g() { - var z = 10; - function h() { - var p = "hello"; - function k() { - var b = "boom"; - } - // Which variables are in scope on this line? - } - - } +Which variables are in scope on the indicated line? + +****************************************************** +variables x, f, y, g, z, h, p and k are in scope (accessible). +variable b is not in scope (not accessible). +***************************************************** + +var x = 5; +function f() { + var y = 8; + function g() { + var z = 10; + function h() { + var p = "hello"; + function k() { + var b = "boom"; + } + // Which variables are in scope on this line? + } + } } \ No newline at end of file diff --git a/src/HOF/problem1.js b/src/HOF/problem1.js index 0ed585e..b341ebc 100644 --- a/src/HOF/problem1.js +++ b/src/HOF/problem1.js @@ -9,6 +9,12 @@ function callNoException(f, arg) { // } // callNoException(throwsZero, 0) returns null // callNoException(throwsZero, 12) returns 12 + try { + f(arg); + } catch (err) { + return null; + } + return f(arg); } function callNoNull(f, arg) { @@ -21,8 +27,8 @@ function callNoNull(f, arg) { // } // callNoNull(nullZero, 0) throws an exception // callNoNull(nullZero, 12) returns 12 - - + if (f(arg) === null) {throw new Error("Argument expected")} + return f(arg); } function exceptionalize(f) { @@ -39,7 +45,11 @@ function exceptionalize(f) { // exceptionalize(nullZero) returns a function g such that // g(0) throws an exception // g(12) returns 12 - + const g = arg => { + if (f(arg) === null) {throw new Error("Argument expected.")} + return f(arg); + } + return g; } function nullify(f) { @@ -55,7 +65,15 @@ function nullify(f) { // nullify(throwsZero) returns a function g such that // g(0) returns null // g(12) throws an exception - + const g = arg => { + try { + f(arg); + } catch (err) { + return null; + } + return f(arg); + } + return g; } function map(lst, f) { @@ -69,6 +87,7 @@ function map(lst, f) { // // function toUpperCase(str) { return str.toUpperCase(); } // map(["bob", "susie"], toUpperCase) returns ["BOB", "SUSIE"] + return lst.map(e => f(e)); } function filter(lst, f) { @@ -82,7 +101,8 @@ function filter(lst, f) { // // Example: // function isEven(x) {return x % 2 == 0;} - // filter([1, 2, 3, 4, 5], isEven) returns [2,4]; + // filter([1, 2, 3, 4, 5], isEven) returns [2,4]; + return lst.filter(e => f(e)); } function every(lst, f) { @@ -92,10 +112,10 @@ function every(lst, f) { // Example // every([2,4,12], x => x % 2 == 0) returns true - // every([2,3,12], x => x % 2 == 0) returns false + // every([2,3,12], x => x % 2 == 0) returns false + return lst.every(e => f(e)); } - module.exports = { callNoException, callNoNull, diff --git a/src/__proto__/problem1.js b/src/__proto__/problem1.js index 820a78d..284453f 100644 --- a/src/__proto__/problem1.js +++ b/src/__proto__/problem1.js @@ -1,6 +1,6 @@ // Make parent the __proto__ of child var parent = {x: 5, y: 6, z: 8}; -var child = {x : 10}; +var child = {x: 10, __proto__: parent}; module.exports = {parent, child} \ No newline at end of file diff --git a/src/anonymous-functions/problem1.js b/src/anonymous-functions/problem1.js index c9cdf24..97f98c6 100644 --- a/src/anonymous-functions/problem1.js +++ b/src/anonymous-functions/problem1.js @@ -1,12 +1,18 @@ -// fix all the errors -function c(g, h) { - var x = g(6); - var y = h(8); - return [x, y]; -} - -function t() { - return c(function (x) {return y + 1}, function (y) {return x * 2}); -} - -module.exports = t; +// fix all the errors +const x = 6; +const y = 8; + +function c(g, h) { + var a = g(x); + var b = h(y); + return [a, b]; +} + +function t() { + return c(function g(x) {return x + 1}, + function h(y) {return y * 2}); +} + +console.log(t()); + +module.exports = t; \ No newline at end of file diff --git a/src/array-functions/problem1.js b/src/array-functions/problem1.js index 06bc426..852f31e 100644 --- a/src/array-functions/problem1.js +++ b/src/array-functions/problem1.js @@ -1,29 +1,36 @@ -function removeEvens(lst) { - // lst is an array of numbers - // Returns a new list with all the even numbers of lst removed -} - -function keepLong(lst) { - // lst is an array of strings - // Returns a new list with all the elements of lst that are length greater than 5 -} - -function greet(lst) { - // lst is an array of strings - // Adds "Hello " to every element of greet - // For example: greet(["bob", "eric"]) returns ["Hello bob", "Hello eric"] -} - -function greetLong(lst) { - // lst is an array of strings - // Only greet people who's names have length at least 4. - // Otherwise ignore them completely. - // For example: greeLong(["bob", "daniel"]) returns ["Hello daniel"] -} - -function allLong(lst) { - // lst is an array of strings - // Returns true if every element of lst is of length at least 5. Otherwise returns false. -} - +function removeEvens(lst) { + // lst is an array of numbers + // Returns a new list with all the even numbers of lst removed + return lst.filter(e => e % 2 !== 0); +} + +function keepLong(lst) { + // lst is an array of strings + // Returns a new list with all the elements of lst that are length greater than 5 + return lst.filter(e => e.length > 5); +} + +function greet(lst) { + // lst is an array of strings + // Adds "Hello " to every element of greet + // For example: greet(["bob", "eric"]) returns ["Hello bob", "Hello eric"] + return lst.map(e => "Hello " + e); +} + +function greetLong(lst) { + // lst is an array of strings + // Only greet people who's names have length at least 4. + // Otherwise ignore them completely. + // For example: greeLong(["bob", "daniel"]) returns ["Hello daniel"] + return lst + .map(e => { if (e.length >= 4) { return "Hello " + e }}) + .filter(e => e !== undefined); +} + +function allLong(lst) { + // lst is an array of strings + // Returns true if every element of lst is of length at least 5. Otherwise returns false. + return lst.every(e => e.length >= 5); +} + module.exports = {removeEvens, keepLong, greet, greetLong, allLong}; \ No newline at end of file diff --git a/src/arrow-functions/problem1.js b/src/arrow-functions/problem1.js index 5c0873a..91f298e 100644 --- a/src/arrow-functions/problem1.js +++ b/src/arrow-functions/problem1.js @@ -1,14 +1,15 @@ -// fix all the errors. -function c(g, h) { - var x = g(6); - var y = h(8, 10); - return [x, y]; -} - -function t() { - return c( x => return y + 2, (x,y) => return x + y); -} - -module.exports = t - - +// fix all the errors. +function c(g, h) { + var x = g(6); + var y = h(8, 10); + return [x, y]; +} + +function t() { + return c(g = (z) => z + 2, + h = (x,y) => x + y); +} + +console.log(t()); // Test file isn't testing anything; but the output is [8, 18], as expected. + +module.exports = t \ No newline at end of file diff --git a/src/arrow-functions/problem2.js b/src/arrow-functions/problem2.js index 1ae3fdb..4406bf5 100644 --- a/src/arrow-functions/problem2.js +++ b/src/arrow-functions/problem2.js @@ -1,10 +1,8 @@ -// Convert all the arrow functions to normal anonymous functions -// There should be no arrows by the end - -var x = x => x + 1; -var y = (x, y) => x + y; -var z = x => {var y = (x * 7) % 2; return y * 2}; - -module.exports = {x, y, z}; - - +// Convert all the arrow functions to normal anonymous functions +// There should be no arrows by the end + +var x = function(x) { return x + 1 }; +var y = function(x, y) { return x + y }; +var z = function(x) { var y = (x * 7) % 2; return y * 2 }; + +module.exports = {x, y, z}; \ No newline at end of file diff --git a/src/bind/problem1.js b/src/bind/problem1.js index da0b2d6..da10aaa 100644 --- a/src/bind/problem1.js +++ b/src/bind/problem1.js @@ -1,7 +1,9 @@ -var bob = {name: "Bob"}; -function greet() { - return "I'm " + this.name; -} -// bind greet to bob - +var bob = {name: "Bob"}; + +function greet() { + return "I'm " + this.name; +} +// bind greet to bob +greet = greet.bind(bob); + module.exports = greet; \ No newline at end of file diff --git a/src/bind/problem2.js b/src/bind/problem2.js index 079a343..e6de549 100644 --- a/src/bind/problem2.js +++ b/src/bind/problem2.js @@ -1,9 +1,8 @@ -// Fix all the errors in this program -var dog = {breed: "schnitzel"}; -function greet() { - return "I'm a " + this.bred; -} - -greet.bind(dog); - +// Fix all the errors in this program +var dog = {breed: "schnitzel"}; +function greet() { + return "I'm a " + this.breed; +} +greet = greet.bind(dog); + module.exports = greet; \ No newline at end of file diff --git a/src/classes/problem1.js b/src/classes/problem1.js index 8e1bcc9..9002d5a 100644 --- a/src/classes/problem1.js +++ b/src/classes/problem1.js @@ -1,7 +1,13 @@ -class Dog { - // Dog has a constructor with three arguments (in this order): age, name and breed - // Dog has three attributes: age, name and breed - // Dog has a method bark, which returns a string -} - +class Dog { + // Dog has a constructor with three arguments (in this order): age, name and breed + // Dog has three attributes: age, name and breed + // Dog has a method bark, which returns a string + constructor(age, name, breed) { + this.age = age; + this.name = name; + this.breed = breed; + } + bark() { return "Woof, bitch!"} +} + module.exports = Dog; \ No newline at end of file diff --git a/src/conditional-operator/problem1.js b/src/conditional-operator/problem1.js index af6e31d..14e438b 100644 --- a/src/conditional-operator/problem1.js +++ b/src/conditional-operator/problem1.js @@ -1,23 +1,5 @@ -//Remove the if statements from these functions. -//Replace them with the conditional operator - - -function desirability(x) { - if(x == 'Brad Pitt') { - return "very desirable"; - } else { - return "not so desirable"; - } -} - -function broadenHorizon(x) { - if(x == 'Brad Pitt') { - return "very desirable"; - } else if(x == 'Angelina Jolie') { - return "also desirable"; - } else { - return "not desirable"; - } -} - +function desirability(x) { return x === 'Brad Pitt' ? "very desirable" : "not so desirable" } + +function broadenHorizon(x) { return x === 'Brad Pitt' ? "very desirable" : x === "Angelina Jolie" ? "also desirable" : "not desirable" } + module.exports = {desirability, broadenHorizon} \ No newline at end of file diff --git a/src/conditional-operator/problem2.js b/src/conditional-operator/problem2.js index 2dd85bf..0755bda 100644 --- a/src/conditional-operator/problem2.js +++ b/src/conditional-operator/problem2.js @@ -1,12 +1,5 @@ -// Remove the conditional operator from these functions -// Replace them with if statements - -function iLike(x) { - return x == 'chinese food' ? true : false; -} - -function iLikeLessPicky(x) { - return x == 'chinese food' ? true : x == 'french food' ? true : false; -} - +function iLike(x) { return x === 'chinese food' } + +function iLikeLessPicky(x) { return x === 'chinese food' || x === 'french food' } + module.exports = {iLike, iLikeLessPicky}; \ No newline at end of file diff --git a/src/constructor-functions/problem1.js b/src/constructor-functions/problem1.js index b39887c..959e14d 100644 --- a/src/constructor-functions/problem1.js +++ b/src/constructor-functions/problem1.js @@ -1,2 +1,4 @@ -// Add a function to all arrays called isNotEmpty -// isNotEmpty returns true is the array is empty, false otherwise +// Add a function to all arrays called isNotEmpty +// isNotEmpty returns true is the array is empty, false otherwise + +Array.prototype.isNotEmpty = function() { return this.length !== 0 } \ No newline at end of file diff --git a/src/exceptions/problem1.js b/src/exceptions/problem1.js index f54c8f8..e67b319 100644 --- a/src/exceptions/problem1.js +++ b/src/exceptions/problem1.js @@ -1,6 +1,15 @@ function first(arr) { // Throw an exception if the array has no elements // Otherwise return the first element + + /* ...Can't use a ternary operator to throw an exception, for some reason... + "[Js] Expression expected" on keyword 'throw'. + */ + if(arr.length <= 0) { + throw new Error("Array is empty!"); + } else { + return arr[0] + }; } function detective(i) { @@ -10,6 +19,12 @@ function detective(i) { // detective checks to see if the suspect throws an exception on input i. // Returns "everything ok" if the suspect doesn't. // Returns "something fishy" if the suspect does. + try { + suspect(i); + } catch(err) { + return "something fishy"; + } + return "everything ok"; } function assignFlight(name) { @@ -17,6 +32,14 @@ function assignFlight(name) { var terrorSuspects = ["bob", "eric", "susie"]; // if the name is a terror suspect, throw an exception // Otherwise, return the flight number + /* ...Can't use a ternary operator to throw an exception, for some reason... + "[Js] Expression expected" on keyword 'throw'. + */ + if (terrorSuspects.includes(name)) { + throw new Error("Name is on blacklist!"); + } else { + return flightNumber; + } } module.exports = {first, detective, assignFlight} \ No newline at end of file diff --git a/src/inheritance/problem1.js b/src/inheritance/problem1.js index 71e66b5..9dd9174 100644 --- a/src/inheritance/problem1.js +++ b/src/inheritance/problem1.js @@ -1,26 +1,35 @@ -class Shape { - toString() { - return "This shape has an area of " + this.area() + " and perimeter " + this.perimeter(); - } -} - -class Rectangle { - - // A rectangle is a shape - // Every rectangle has a width and a height - // Implement the constructor - // Implement the area and perimeter methods - // The constructor has two arguments: width and height -} - -class Square { - // A square is a rectangle - // Every square has a width and a height - // The height and width of a square are always the same - // Implement the constructor - // Do not implement the area and perimeter methods. They should be inherited from Rectangle - // The constructor has one argument -} - - +class Shape { + toString() { + return "This shape has an area of " + this.area() + " and perimeter " + this.perimeter(); + } +} + +class Rectangle extends Shape { + // A rectangle is a shape + // Every rectangle has a width and a height + // Implement the constructor + // Implement the area and perimeter methods + // The constructor has two arguments: width and height + constructor(width, height) { + super(); + this.width = width; + this.height = height; + } + area() { return this.width * this.height } + perimeter() { return (this.width + this.height) * 2 } +} + +class Square extends Rectangle { + // A square is a rectangle + // Every square has a width and a height + // The height and width of a square are always the same + // Implement the constructor + // Do not implement the area and perimeter methods. They should be inherited from Rectangle + // The constructor has one argument + constructor(side) { + super(side, side); + this.side = side; + } +} + module.exports = {Shape, Rectangle, Square}; \ No newline at end of file diff --git a/src/inheritance/problem2.js b/src/inheritance/problem2.js index f74dc6b..34874b9 100644 --- a/src/inheritance/problem2.js +++ b/src/inheritance/problem2.js @@ -1,26 +1,26 @@ -// Correct all the mistakes in this file - -class Shape { - constructor(shapeName) { - this.shapName = shapeName; - } - toString() { - return this.shapeName + " with area " + - this.area() + " and perimeter " + this.permeter(); - } -} - -class Square { - constructor(size) { - supr("square"); - this.size = size; - } - area() { - return this.size * this.siz; - } - perimeter() { - return this.size * 4; - } -} - +// Correct all the mistakes in this file + +class Shape { + constructor(shapeName) { + this.shapeName = shapeName; + } + toString() { + return this.shapeName + " with area " + + this.area() + " and perimeter " + this.perimeter(); + } +} + +class Square extends Shape { + constructor(size) { + super("square"); + this.size = size; + } + area() { + return this.size * this.size; + } + perimeter() { + return this.size * 4; + } +} + module.exports = {Shape, Square}; \ No newline at end of file diff --git a/src/problem1.js b/src/problem1.js new file mode 100644 index 0000000..94b49f6 --- /dev/null +++ b/src/problem1.js @@ -0,0 +1,4 @@ +// Fix all the errors. It should print hello after 1 second +let myString = "hello"; +function shout(x) { console.log(this.sayWhaaat) } +setTimeout(shout.bind({sayWhaaat: myString}), 1000); \ No newline at end of file diff --git a/src/return/problem1.js b/src/return/problem1.js index c8f7b32..2c9021a 100644 --- a/src/return/problem1.js +++ b/src/return/problem1.js @@ -1,17 +1,2 @@ -// Remove as many characters from this function without changing its meaning. -// In other words, make this function as succinct as possible -// Also, remove these comments - -function f(x) { - if(x > 10) { - return "hello"; - } else if(x > 5) { - return "goodbye"; - } else { - return undefined; - } -} - -module.exports = f; // Don't delete this line but remove this comment. - - +const f = x => x > 10 ? "hello" : x > 5 ? "goodbye" : undefined +module.exports = f \ No newline at end of file diff --git a/src/this/problem1.js b/src/this/problem1.js index b7b2740..5dce905 100644 --- a/src/this/problem1.js +++ b/src/this/problem1.js @@ -1,6 +1,7 @@ -'use strict'; -function whatsMyAgeAgain() { - // returns this.age unless this is not defined. If this is not defined, return 18 -} - +'use strict'; +function whatsMyAgeAgain() { + // returns this.age unless this is not defined. If this is not defined, return 18 + return this === undefined ? 18 : this.age; +} + module.exports = whatsMyAgeAgain; \ No newline at end of file diff --git a/src/variable-scoping/problem1.js b/src/variable-scoping/problem1.js index da8f429..f4cacf7 100644 --- a/src/variable-scoping/problem1.js +++ b/src/variable-scoping/problem1.js @@ -1,12 +1,9 @@ -// Fix this function. -// It should return a different number every time it is called -// The first time it is called it returns 1 -// Every call thereafter returns a number one greater than the last - -function f() { - var x = 0; - x = x + 1; - return x; -} - +// Fix this function. +// It should return a different number every time it is called +// The first time it is called it returns 1 +// Every call thereafter returns a number one greater than the last + +let x = 0; +function f() { x = x + 1; return x } + module.exports = f; \ No newline at end of file