Javascript

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

function Dog() { this.name = "Rupert"; this.color = "brown"; this.numLegs = 4; } let hound = new Dog function Dog(name, color) { this.numLegs = 4 this.name = name this.color = color } let terrier = new Dog("Lil Shit","brown")

A function which creates objects is called a constructor and is usually capitalized to distinguish it. Using this refers to the context of where it is. Remeber functions are objects. This inside of the dog function refers to dog. This outside of the function in the global scope or the root context refers to the window. You can create a new object that is a copy of another by setting the new name equal to new function. It would appear this method does not work for variable defined normal objects, only functions. You can also create a template to reuse for example.

function largestOfFour(arr) { let largeArray = [] for (let i = 0; i < arr.length; i++) { largeArray.push(Math.max(...arr[i])) } return largeArray; } console.log(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]])); // returns 5,27,39,1001

An issue I had was figuring out why Math.max was returning NaN for (arr[i]) but after research figured out it needed the spread operator because it can't process Math.max([1, 2, 3]) // returns NaN

function glideMixin(obj) { obj.glide = function() { console.log("Gliding on the water"); }; } function flyMixin(obj) { obj.fly = function() { console.log("Flying, wooosh!"); }; } //////////////////////////////////////////////////// let motionModule = (function () { return { glideMixin: function (obj) { // Instead of equaling the function, it is set to it because this is now an object obj.glide = function() { console.log("Gliding on the water"); }; }, // Also don't forget the comma separating the two entries flyMixin: function(obj) { // Same here obj.fly = function() { console.log("Flying, wooosh!"); }; } } }) (); // The two parentheses cause the function to be immediately invoked

By using IIFE you can create modules which can combine multiple things into a single package you can use elsewhere in your code. It is basically a complex function.

function Animal() { } Animal.prototype = { constructor: Animal, eat: function() { console.log("nom nom nom"); } }; let duck = Object.create(Animal.prototype) let beagle = Object.create(Animal.prototype) duck.eat(); // Should print "nom nom nom" beagle.eat(); // Should print "nom nom nom"

By using Object.create(OBJECT) It is another way to create instead of using new OBJECT which apparently has some disadvantages I am not aware of yet.

function Bird() { let weight = 15; this.getWeight = () => {return weight} } let tree = new Bird console.log(tree.getWeight)

By utilizing closure we can create private variables which can't be accessed from outside the function. Only code within the function can access it. In the example this.getWeight is the only way we can interact with weight outside of the function. We cannot modify it at all, only return.

function mutation(arr) { let lowerCase1 = arr[0].toLowerCase() let lowerCase2 = arr[1].toLowerCase() let splitStr1 = lowerCase1.split("") let splitStr2 = lowerCase2.split("") for (let i = 0; i < splitStr2.length; i++) { if (lowerCase1.includes(splitStr2[i])) { } else { return false } } return true } console.log(mutation(["Mary", "Aarmy"]));

I had fun with this one. I took time to look at different methods I might potentially use (surveying my toolbox if you will) then I thought it out, coded, debugged, and then it worked like I thought it would.

let flyMixin = function(obj) { obj.fly = function() { console.log("Flying, wooosh!"); } }; let bird = { name: "Donald", numLegs: 2 }; let plane = { model: "777", numPassengers: 524 }; flyMixin(bird); flyMixin(plane); bird.fly(); // prints "Flying, wooosh!" plane.fly(); // prints "Flying, wooosh!"

For unrelated objects, it's better to use mixins. A mixin allows other objects to use a collection of functions. It is basically an isolated property which you can add to your new objects.

const prepareGreenTea = () => 'greenTea'; // Callback, first class function const prepareBlackTea = () => 'blackTea'; // Callback, first class function const getTea = (prepareTea, numOfCups) => { // higher order function const teaCups = []; for(let cups = 1; cups <= numOfCups; cups += 1) { const teaCup = prepareTea(); teaCups.push(teaCup); } return teaCups; }; const tea4GreenTeamFCC = getTea(prepareGreenTea, 27); // :( const tea4BlackTeamFCC = getTea(prepareBlackTea, 13); // :( console.log( tea4GreenTeamFCC, tea4BlackTeamFCC );

Functions are first class objects. We already know function are objects after all, which means they can be used like any other object. They can be saved in variables, stored in an object, or passed as function arguments. Callbacks are the functions that are slipped or passed into another function to decide the invocation of that function. Functions that can be assigned to a variable, passed into another function, or returned from another function just like any other normal value, are called first class functions. In JavaScript, all functions are first class functions. The functions that take a function as an argument, or return a function as a return value are called higher order functions. When the functions are passed in to another function or returned from another function, then those functions which gets passed in or returned can be called a lambda.

function Dog(name) { this.name = name; } Dog.prototype = { constructor: Dog, // Sets the forgotten constructor numLegs: 4, eat: function() { return "eat" }, describe: function() { return "decrivbe" }, arrow: () => {return "arroE"} }; let puupy1 = new Dog('Antonio') console.log(puupy1.name, puupy1.arrow)

Here is how to use Arrow functions. And how to create many properties for a prototype by creating an object. An issue with defining a prototype object is that it removes the constructor property. So if you don't define it within the prototype object then it will return undefined.

function getIndexToIns(arr, num) { let arrSorted = arr.sort((a, b) => a - b) if (arrSorted == "") { return 0 } for(let i = 0; i < arrSorted.length; i++) { if (arrSorted[i] >= num) { return i } else if (i == arrSorted.length - 1) { return arrSorted.length } } } console.log(getIndexToIns([], 1));

I am having a hard time understanding why this doesn't give me zero. EDIT: So it was because arrSorted did not have a value. I initially tried to do: if (arrSorted == String) { return 0 } or if (arrSorted == typeof string) { return 0 } It may have been capitalization for why it did nt work but I don't care to test right now. But ultimately I tried this if (arrSorted == "") { return 0 }

function frankenSplice(arr1, arr2, n) { let arr2Index = arr2.slice(n) arr2Index.unshift(arr1) arr2Index.unshift(arr2.slice(0,n)) return arr2Index; } console.log(frankenSplice([1, 2, 3], [4, 5], 1));

I created a function which basically inserts arr1 into arr2 at n index. On FCC it doesn't pass even though it always outputs the right information. I believe it is because I didn't use splice as per requested but I don't see the need.

function bouncer(arr) { function CHECK(ARR) { if (ARR === null || false || 0 || undefined || NaN || ""){ return } else { return ARR } } return arr.filter(CHECK); } console.log(bouncer([false, null, 0, NaN, undefined, ""]));

I created a function which just returns the ARR if it is not the specified things. Then I take that and filter it to an array set which will automatically give me a new array of all my nice data for me. The fast solution is simply: return arr.filter(Boolean)

function destroyer(target, ...destroyer) { let missiles = destroyer var answer = target for (let i = 0; i < destroyer.length; i++){ var answer = answer.filter(function(missiles) { return missiles != destroyer[i] })} return answer } console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));

I created this program which returns the array without the arguments specified. It may be inefficient because it runs through target as many times as there are arguments you want to get rid of.

function confirmEnding(str, target) { let targReg = new RegExp(target + '($)') return targReg.test(str); } console.log(confirmEnding("Bastian", "n"));

I used a regex in order to find if a given target was at the end of the string. I had to learn how to put a variable into a regex. Using the RegExp we can add variables, it just makes it a little more complex because we have to include other non-variable portions inside '()' / "()"

function makeNest() { console.log("A cozy nest is ready"); } makeNest(); /////////////// (function () { console.log("A cozy nest is ready"); })();

IIFE or immediately invoked function expression is a way to execute a function without having to call it. The example below is the IIFE version of the function above.

function Animal() { } Animal.prototype = { constructor: Animal, eat: function() { console.log("nom nom nom"); } }; function Dog() { } Dog.prototype = Object.create(Animal.prototype) let beagle = new Dog(); beagle.eat(); // Should print "nom nom nom"

In creating supertypes the constructor Object should have its .prototype = Object.create(Animal.prototype) So it inherits the information for Animal. The problem is that when you check the constructor for an object created by that constructor which inherited properties from another object or prototype, that object or prototype will show up as the constructor and not the constructor we used to create it in the first place. There are multiple way you can do this but one such way would be: CONSTRUCTOR.prototype.constructor = CONSTRUCTOR

Immediately Invoked Function Expressions (IIFEs) Instead of calling a function there's another way to execute a function expression, which is typically referred to as an immediately invoked function expression(IIFE): (function IIFE( ) { console.log( "Hello!" ); })( ); // "Hello!" The outer ( .. ) that surrounds the (function IIFE(){ .. }) function expression is just a nuance of JS grammar needed to prevent it from being treated as a normal function declaration. The final () on the end of the expression -- the })(); line -- is what actually executes the function expression referenced immediately before it.

It makes sense. IIFE(); // This would call the function. ( entireFunction )(); // This would also call the function in the same way as shown.

Regular Expressions: Restrict Possible Usernames let username = "JackOfAllTrades"; let userCheck = /^[a-z]{2,}\d*$/i; let result = userCheck.test(username); console.log(result)

It works because it is looking for any letter between the position 2 and infinity. Meaning if there is no position 2 then it will not pass. It continues to check for letters to the end where we have another part that looks for 0 or more numbers at the end. If there was any number that was not at the end it would break the search for letters and return false.

Regular expressions are used in programming languages to match parts of strings. You create patterns to help you do that matching. You can find whether or not a string contains a word by using a Regex: /word/. You can customize the search by using the OR:" | " operator. i.e. /dog | cat | ice/ Adding the i flag to the end of the regex makes it search regardless of case. let myString = "Hello, World!"; let myRegex = /Hello | test/i; let result = myRegex.test(myString);

JavaScript has multiple ways to use regexes. One way to test a regex is using the .test() method. The .test() method takes the regex, applies it to a string (which is placed inside the parentheses), and returns true or false if your pattern finds something or not.

Sometimes whitespace characters around strings are not wanted but are there. Typical processing of strings is to remove the whitespace at the start and end of it. Write a regex and use the appropriate string methods to remove whitespace at the beginning and end of strings. Note The .trim() method would work here, but you'll need to complete this challenge using regular expressions. let hello = " Hello, World! "; let wsRegex = /\w+.?\s\w+.?/ig; // Change this line let result = hello.match(wsRegex); // Change this line console.log(result);

My own solution. Woo!

function spinalCase(str) { let underscoreSplit = str.split("_") let underscoreJoin = underscoreSplit.join(" ") let hyphenSplit = underscoreJoin.split("-") let hyphenJoin = hyphenSplit.join(" ") let regex = "[A-Z]" let re = new RegExp(regex, "g") let letters = hyphenJoin.match(re) let index = [] for(let i = 0; i < letters.length; i++) { for(let j = 0; j < index.length; j++){ if (hyphenJoin.indexOf(letters[i]) == index[j]) { index.push(hyphenJoin.indexOf(letters[i], hyphenJoin.indexOf(letters[i]) + 1)) }} index.push(hyphenJoin.indexOf(letters[i])) } let uniq = index.reduce(function(a,b){ if (a.indexOf(b) < 0 ) a.push(b); return a; },[]) // Now I need to check is there is a space to the left of the indexed value, if not add one then return // Also don't forget to trim var together = hyphenJoin for(let z = 0; z < uniq.length; z++) { if(together[uniq[z] - 1] == " ") { }else { let portion1 = together.substring(0, uniq[z] + z) let portion2 = together.substring(uniq[z]+z) var together = portion1.concat(" ", portion2) console.log(together) } } return together.trim().split(" ").filter(word => word.length > 0).join("-").toLowerCase() } console.log(spinalCase("This Is Spinal Tap"));

My very inefficient code.

let testArr = ["Blue", "Red", "Yellow"] let test1 = [] test1.push(testArr) console.log(test1[0]) // "Blue", "Red", "Yellow" let TESTARR = [["Blue", "Red", "Yellow"]] console.log(TESTARR[0]) // "Blue", "Red", "Yellow" let testArr = ["Blue", "Red", "Yellow"] let test1 = [] test1.push(...testArr) // By using the spread it breaks it the testArr into test1 console.log(test1[0]) // "Blue"

Pertaining to .push I recently learned that if you take an array and .push it into an empty array it ends up placing that entire array into the empty array as arr[0] for the entire array. A visualization of what is occurring can be see in my example I used to deduce this. EDIT: The way to fix this is to use the spread operator in order to ensure that it is only one array and not an array within an array.

let rating = watchList.map(item => ({ "title": item["Title"], "rating": item["imdbRating"] }) )

So this is a mapped function over an object. The function within the map takes an object and assigns what it finds under VARIABLE["Title"] and setting it to "title". This is valid because functions are objects. Because it is a map it will return an array of objects that it created with information it collected from all of the sub objects.

function Dog(name) { this.name = name; } Dog.prototype.numLegs = 4 let beagle = new Dog("Snoopy"); console.log(beagle.numLegs) function Dog(name) { this.name = name; } Dog.prototype.numLegs = 4; let beagle = new Dog("Snoopy"); let ownProps = []; let prototypeProps = []; for (let property in beagle) { if (beagle.hasOwnProperty(property)) { // Seperates Own from prototype ownProps.push(property) } else { prototypeProps.push(property) } }

Prototype is like a recipe that all objects created using the constructor that has a property defined with prototype will have it. It is in contrast to the Own property which is defined directly on the object instance itself. And prototype properties are defined on the prototype. Basically what that means is that when an object has the same information for a property in all the objects you produce from a constructor then you are creating the same variable every time and are wasting resources. By using CONSTRUCTOR.prototype.PROPERTY all objects from that constructor will get the information from the recipe/prototype instead of the created object itself and will save time and space. I don't know whether it should be defined inside the constructor or not. Probably outside because it is not an Own property? Yes, because .hasOwnProperty does not return true for prototypes.

let Bird = function(name, color) { this.name = name; this.color = color; this.numLegs = 2; } let crow = new Bird("Alexis", "black"); crow instanceof Bird; // => true

You can use instanceof to determine if an object was created by a particular constructor.

function repeatStringNumTimes(str, num) { let endResult = [] for (let i = 0; i < num; i++) { endResult.push(str) } endResult.join("") //return this not just return endResult return endResult.join(""); } console.log(repeatStringNumTimes("abc", 3));

The issue I had with this simple function was not returning the: endResult.join("") and just returning: endResult

let ohStr = "Ohhh no"; let ohRegex = /oh{3,6}\sno/i; let result = ohRegex.test(ohStr); Your regex should not match "Ohhhhhhh no"

The reason we need to specify the o before h is that if there is no o then it would skip as many h characters as it likes to make it true. The \s is whitespace and because this example is not many different permutations we could lazily hard code the whitespace into it: /oh{3,6} no/i This is naive but would work for this example.

do... while is another way to loop code. var myArray = []; var i = 10; do { myArray.push(i); i++; } while (i < 5);

The only difference between using do ... while versus just while is that using do allows the code to run once before checking if the conditions for a second time are true.

function titleCase(str) { let titled = [] for (let i = 0; i < str.split(' ').length; i++) { let splitStr = str.split(' ') let word = splitStr[i] let firstChar = word.charAt(0) let capFirstChar = firstChar.toUpperCase() let lowerLetters = word.slice(1).toLowerCase() let capWord = capFirstChar + lowerLetters titled.push(capWord) } return titled.join(" ") } console.log(titleCase("I'm king BUT WHAT ABOUT ME"));

The only real issue I had was trying to see if there was some operation to make life easier. I did not find it. Try this again with regex.

function ascendingOrder(arr) { return arr.sort(function(a, b) { return a - b; }); } ascendingOrder([1, 5, 2, 3, 4]); // Returns [1, 2, 3, 4, 5] function reverseAlpha(arr) { return arr.sort(function(a, b) { return a < b; }); } reverseAlpha(['l', 'h', 'z', 'b', 's']); // Returns ['z', 's', 'l', 'h', 'b']

The sort method sorts the elements of an array according to the callback function. Sort also modifies the original array.

let duck = new Bird(); let beagle = new Dog(); console.log(duck.constructor === Bird); //prints true console.log(beagle.constructor === Dog); //prints true function Dog(name) { this.name = name; } function joinDogFraternity(candidate) { if(candidate.constructor === Dog) { return true } else { return false } }

There is a special constructor property located on the object instances of the objects created by constructors. The .constructor returns true of false.

function zeroArray(m, n) { // Creates a 2-D array with m rows and n columns of zeroes let newArray = []; let row = []; for (let i = 0; i < m; i++) { // Adds the m-th row into newArray for (let j = 0; j < n; j++) { // Pushes n zeroes into the current row to create the columns row.push(0); } // Pushes the current row, which now has n zeroes in it, to the array newArray.push(row); } return newArray; } let matrix = zeroArray(3, 2); console.log(matrix);

Try to understand this function better

function Bird(name) { this.name = name; this.numLegs = 2; } let canary = new Bird("Tweety"); let ownProps = []; for (let property in canary) { if (canary.hasOwnProperty(property)){ ownProps.push(property) } } console.log(ownProps) // name,numLegs

Using a for in statement we can iterate over all non-Symbol, enumerable properties of an object. Then you can do what you want with the result.

function chunkArrayInGroups(arr, size) { let result = [] let j = 1 for (let i = 0; i < size * Math.floor(arr.length / size + 0.99999999); i += size) { do { result.push(arr.slice(i, j * size)) j++ console.log(j) } while (j < i / size -423) } return result } console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2));

WOOOOOOOOOOOOOOOO!!!

function splitify(str) { return str.split(/[^\w]/) // (/\W/) is also valid } console.log(splitify("Hello World,I-am code")); //Hello,World,I,am,code

When using split you can use regular expressions on them as well. It is useful because strings are immutable .

function Bird(name) { this.name = name; } let duck = new Bird("Donald"); Bird.prototype.isPrototypeOf(duck); // returns true

You can check if a prototype comes from a constructor by using: CONSTRUCTOR.prototype.isPrototypeOf(OBJECT) Side note: There can be multiple levels to prototypes going very deep. Also all objects have a prototype. For example, Bird is the prototype of duck. Object.prototype is the prototype of Bird.prototype. Object.prototype is a supertype for all objects.

What does it look like inside of a string when you want a " in the print? (Take this and ashow the different ways)

\"

if (strokes = 4) { return "Hole-in-one!"; } else if (strokes = par - 2) { return "Eagle"; } else if (par - 1 <= strokes) { return "Birdie"; } else if (strokes = par) { return "Par"; } else if (strokes = par + 1) { return "Bogey"; } else if (strokes = par + 2) { return "Double Bogey"; } else { return "Go Home!"; } return "Change Me";

figure why using == works but not = I think it is because == and === both produce either a true or false because they are boolean values, while the = is not boolean.

Lookaheads are patterns that tell JavaScript to look-ahead in your string to check for patterns further along. This can be useful when you want to search for multiple patterns over the same string. There are two kinds of lookaheads: positive lookahead and negative lookahead. A positive lookahead will look to make sure the element in the search pattern is there, but won't actually match it. A positive lookahead is used as (?=...) where the ... is the required part that is not matched. On the other hand, a negative lookahead will look to make sure the element in the search pattern is not there. A negative lookahead is used as (?!...) where the ... is the pattern that you do not want to be there. The rest of the pattern is returned if the negative lookahead part is not present. Lookaheads are a bit confusing but some examples will help. let quit = "qqquit"; let quRegex= /qq(?=u)/; console.log(quit.match(quRegex)); // Returns ["qq"] let noquit = "qte"; let qRegex = /q(?!u)/; console.log(noquit.match(qRegex)); // Returns ["q"] let sampleWord = "astronaut"; let pwRegex = /(?=\w{5,})(?=\D*\d{2})/; let result = pwRegex.test(sampleWord); // Searches for at least 5 characters and exactly 2 consecutive digits

I think the point of using lookaheads is that it will never match the statements (after the operator is actually used). I think this is a useful feature for security.

In regular expressions, a greedy match finds the longest possible part of a string that fits the regex pattern and returns it as a match. The alternative is called a lazy match, which finds the smallest possible part of the string that satisfies the regex pattern. You can apply the regex /t[a-z]*i/ to the string "titanic". This regex is basically a pattern that starts with t, ends with i, and has some letters in between. Regular expressions are by default greedy, so the match would return ["titani"]. It finds the largest sub-string possible to fit the pattern. However, you can use the ? character to change it to lazy matching. "titanic" matched against the adjusted regex of /t[a-z]*?i/ returns ["ti"].

Not sure if the positioning of the ? is important or not. At least don't mix it with the letters or it will be similar to the star * for the preceding element

You can search for a literal pattern with some flexibility with character classes. Character classes allow you to define a group of characters you wish to match by placing them inside square ([ and ]) brackets. REMEMBER the brackets. let quoteSample = "Beware of bugs in the above code; I have only proved it correct, not tried it."; let vowelRegex = /[aeiou]/ig; let result = quoteSample.match(vowelRegex); // result: e,a,e,o,u,i,e,a,o,e,o,e,I,a,e,o,o,e,i,o,e,o,i,e,i let bigStr = "big"; let bogStr = "bog"; let bgRegex = /b[aiu]g/; bigStr.match(bgRegex); // Returns ["big"] bogStr.match(bgRegex); // Returns null

Remember letters go outside the /./

There's also an option that matches characters that occur zero or more times. The character to do this is the asterisk or star: *. let chewieQuote = "Aaaaaaaaaaaaaaaarrrgh!"; let chewieRegex = /Aa*/; // Change this line let result = chewieQuote.match(chewieRegex); console.log(result) Aaaaaaaaaaaaaaaa

The reason the star is needed is because it unifies the letters that meet the requirement into one string.


Ensembles d'études connexes

Prepu: Chapter 8: Atraumatic Care of Children and Families

View Set

6.5 IB Biology- Neurons and Synapses

View Set