FCC Algorithm

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

Make a Person Fill in the object constructor with the following methods below: getFirstName() getLastName() getFullName() setFirstName(first) setLastName(last) setFullName(firstAndLast) Run the tests to see the expected output for each method. The methods that take an argument must accept only one argument and it has to be a string. These methods must be the only available means of interacting with the object.

var Person = function(firstAndLast) { var fullName = firstAndLast; this.getFirstName = function() { return fullName.split(" ")[0]; }; this.getLastName = function(){ return fullName.split(" ")[1]; this.getFullName = function(){ return fullName; }; this.setFirstName = function(name) { fullName = name + " " + fullName.split(" ")[1]; }; this.setLastName = function(name) { fullname = fullName.split(" ")[0] + " " + name;}; this.setFullName = function(name) { fullName = name; }; }; var bob = new Person('Bob Ross'); bob.getFullName();

Exact Change Design a cash register drawer function checkCashRegister() that accepts purchase price as the first argument (price), payment as the second argument (cash), and cash-in-drawer (cid) as the third argument. cid is a 2D array listing available currency. Return the string "Insufficient Funds" if cash-in-drawer is less than the change due. Return the string "Closed" if cash-in-drawer is equal to the change due. Otherwise, return change in coin and bills, sorted in highest to lowest order function checkCashRegister(price, cash, cid) { } checkCashRegister(19.50, 20.00, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.10], ["QUARTER", 4.25], ["ONE", 90.00], ["FIVE", 55.00], ["TEN", 20.00], ["TWENTY", 60.00], ["ONE HUNDRED", 100.00]]) ;

var money = [ {name: 'ONE HUNDRED', value: 100.00}, {name: 'TWENTY', value: 20.00}, {name: 'TEN', value: 10.00}, {name: 'FIVE', value: 5.00}, {name: 'ONE', value: 1.00}, {name: 'QUARTER', value: 0.25}, {name: 'DIME', value: 0.10}, {name: 'NICKEL', value: 0.05}, {name: 'PENNY', value: 0.01} ]; function checkCashRegister(price, cash, cid) { var rest = cash - price; // calculate total money in cid var total = cid.reduce(function(acc, next) { return acc + next[1]; }, 0.0); // check drawer if ( total < rest ) { return "Insufficient Funds"; } if (total === rest ) { return "Closed"; } // extract change from funds cid = cid.reverse(); var result = money.reduce(function(acc, next, index) { if ( rest >= next.value) { var currentValue = 0.0; while( rest >= next.value && cid[index][1] >= next.value) { currentValue += next.value; rest -= next.value; cid[index][1] -= next.value; rest = Math.round(rest *100) /100; } acc.push([next.name, currentValue]); return acc; } else { acc; } }, []); return result.length > 0 && rest === 0 ? result: "Insufficient Funds"; }

Map the Debris intermidiate colution function orbitalPeriod(arr) { var GM = 398600.4418; var earthRadius = 6367.4447; //loop through each key in array object for(var prop in arr) { //rouding off the orbital period value var orbitalPer = Math.round(2 * Math.PI * Math.sqrt(Math.pow(arr[prop].avgAlt + earchRadius,3) /GM)); // deleting the avgAlt property delete arr[prop].avgAlt; //adding orbitalPeriod property arr[prop].orbitalPeriod = orbitalPer; } return arr; } // test here orbitalPeriod([{name : "sputnik", avgAlt : 35873.5553}]);

Map the Debris advanced solution function orbitalPeriod(arr) { var GM = 398600.4418; var earthRadius = 6367.4447; arr.forEach(function(item){ var tmp = Math.round(2* Math.PI * Math.sqrt(Math.pow(earthRadius + item.avgAlt,3)/GM)); delete item.avgAlt; item.orbitalPeriod = tmp; }); return arr; } // test here orbitalPeriod([{name : "sputnik", avgAlt : 35873.5553}]);

No repeats please

freecode camp solution // create a regex var regex = /(.)\1+/g; //split the string into an array var arr = str.split(''); var permutations = []; var tmp; //return 0 if str contains same character if(str.match(regex)! == null && str.match(regex)[0] === str) return 0; //function to swap variable content. function swap(index1, index2){ temp = arr[index1]; arr[index1] = arr[index2]; arr[index2] = temp; } //generate arrays of permutations using the algorithm function generate(int) { if(int ===1) { //make sure to join the characters aw we create the permutation arrays permutations.push(arr.join(''); } else { for(var i=0; i!=int; ++i){ generate(int-1); swap(int%2?0:i,int-1); } } } generate(arr.length); //filter the array of repeated permutations var filterd = permutations.filter(function(string) { return !string.match(regex); }); return filtered.length; }

Arguments Optional Create a function that sums two arguments together. If only one argument is provided, then return a function that expects one argument and returns the sum. For example, addTogether(2, 3) should return 5, and addTogether(2) should return a function. Calling this returned function with a single argument will then return the sum: var sumTwoAnd = addTogether(2); sumTwoAnd(3) returns 5. If either argument isn't a valid number, return undefined.

function addTogether() { var args = new Array(arguments.length); // store the arguments in an array for(var i=0; i<args.length; ++i){ args[i] = arguments[i]; } // check for the arguments length if(args.length == 2) { if(typeof args[0] !== 'number' || typeof args[1] !== 'number') { return undefined; } return args[0] + args[1]; } // when only one arguent is provided if(args.length ==1 ) { a = args[0]; if(typeof a!=='number') { return undefined; } else { //closure return function(b) { if (typeof b !== 'number') { return undefined; } else return a + b; }; } } } // test here addTogether(2,3);

Binary Agents Return an English translated sentence of the passed binary string. The binary string will be space separated. function binaryAgent(str) { } binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111");

function binaryAgent(str) { result=[]; newstr = str.split(' '); for(var i=0; i<newstr.length; i++) { result.push(String.fromCharCode(parseInt(newstr[i],2))); } return result.join(""); } or function binaryAgent(str){ return String.fromCharCode(...str.split(' ').map(function(char){ return parseInt(char, 2); })); }

Falsy Bouncer Remove all falsy values from an array. Falsy values in JavaScript are false, null, 0, "", undefined, and NaN. function bouncer(arr) { } bouncer([7, "ate", "", false, 9]);

function bouncer(arr) { return arr.filter(Boolean); } bouncer([7, "ate", "", false, 9]);

Chunky Monkey Write a function that splits an array (first argument) into groups the length of size (second argument) and returns them as a two-dimensional array. function chunkArrayInGroups(arr, size) { } chunkArrayInGroups(["a", "b", "c", "d"], 2);

function chunckArrayInGroups(arr,size) { var newArray = []; for(var i = 0; i < arr.length; i+= size) { newArray.push(arr.slice( i, size+i)); } return newArray; } chunkArrayInGroups(["a", "b", "c", "d"], 2);

Confirm the Ending Check if a string (first argument, str) ends with the given target string (second argument, target). This challenge can be solved with the .endsWith() method, which was introduced in ES2015. But for the purpose of this challenge, we would like you to use one of the JavaScript substring methods instead. function confirmEnding(str, target) { } confirmEnding("Bastian", "n");

function confirmEnding(str , target) { if(str.substr(-target.length) == target) { return true; } else { return false; } } confirmEnding("Bastian", "n");

Convert HTML Entities Convert the characters &, <, >, " (double quote), and ' (apostrophe), in a string to their corresponding HTML entities. function convertHTML(str) { // &colon;&rpar; var result = str.split(''); for (var i=0; i<result.length; i++){ } convertHTML("Dolce & Gabbana");

function convertHTML(str) { // &colon;&rpar; var result = str.split(''); for (var i=0; i<result.length; i++){ switch (result[i]) { case '&': result[i]='&amp;'; break; case '<': result[i]='&lt;'; break; case '>': result[i]='&gt;'; break; case '"': result[i]='&quot;'; break; case "'": result[i]='&apos;'; break; } } result = result.join(''); return result; } convertHTML("Dolce & Gabbana");

Seek and Destroy You will be provided with an initial array (the first argument in the destroyer function), followed by one or more arguments. Remove all elements from the initial array that are of the same value as these arguments. function destroyer(arr) { } destroyer([1, 2, 3, 1, 2, 3], 2, 3);

function destroyer(arr) { var args = Array.prototype.slice.call(arguments); args.splice(0,1); return arr.filter(function(element) { return args.indexOf(element) === -1; }); } destroyer([1, 2, 3, 1, 2, 3], 2, 3);

Compare two arrays and return a new array with any items only found in one of the two given arrays, but not both. In other words, return the symmetric difference of the two arrays. function diffArray(arr1, arr2) { var newArr = []; return newArr; } diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);

function diffArray(arr1, arr2) { var newArr = []; // Looping through arr1 to find elements that do not exist in arr2 for (var i = 0; i < arr1.length; i++) { if (arr2.indexOf(arr1[i]) === -1){ // Pushing the unique to arr1 elements to the newArr newArr.push(arr1[i]); } } // Looping through arr2 to find elements that do not exist in arr1 for (var j = 0; j < arr2.length; j++) { if (arr1.indexOf(arr2[j]) === -1){ // Pushing the unique to arr2 elements to the newArr newArr.push(arr2[j]); } } return newArr; } diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);

Algorithm Drop It Drop the elements of an array (first argument), starting from the front, until the predicate (second argument) returns true. The second argument, func, is a function you'll use to test the first elements of the array to decide if you should drop it or not. function dropElements(arr, func) { } return arr; } dropElements([1, 2, 3, 4], function(n) {return n > 5;});

function dropElements(arr,func) { var num = arr.length; for (var i =0; i<num; i++) { if(func(arr[0]) === false ) { arr.shift(); } else { return arr; } } return arr; } dropElements([1, 2, 3, 4], function(n) {return n > 5;});

Return the factorial of the provided integer. If the integer is represented with the letter n, a factorial is the product of all positive integers less than or equal to n. Factorials are often represented with the shorthand notation n! For example: 5! = 1 * 2 * 3 * 4 * 5 = 120 function factorialize(num) { } factorialize(5);

function factorialize(num) { var factorial = 1; for ( var n = 2; n <=num; n++) { factorial = factorial *n;} return factorial; } factorialize(5);

Missing letters Find the missing letter in the passed letter range and return it. If all letters are present in the range, return undefined. function fearNotLetter(str) { for (var i=0; i<str.length; i++){ var code = str.charCodeAt(i); if (code !== str.charCodeAt(0) +i ){ return String.fromCharCode(code-1); } } return undefined; } fearNotLetter("abce");

function fearNotLetter(str) { for (var i=0; i<str.length; i++) { var code = str.charCodeAt(i); if(code!== str.charCodeAt(0) +i) { return String.fromCharCode(code-1); } } return undefined; } fearNotLetter("abce");

Finders Keepers Create a function that looks through an array (first argument) and returns the first element in the array that passes a truth test (second argument). function findElement(arr, func) { } findElement([1, 3, 5, 8, 9, 10,20], function(num){ return num % 5 === 0; });

function findElement(arr, func) { var num = 0; num = arr.filter(func); num.splice(1); return num[0]; } findElement([1, 3, 5, 8, 9, 10,20], function(num){ return num % 5 === 0; });

Return the length of the longest word in the provided sentence. Your response should be a number. function findLongestWord(str) { } findLongestWord("The quick brown fox jumped over the lazy dog");

function findLongestWord(str) { var splitWord = str.split(' '); var longestWord = 0; for(var i=0; i < splitWord.length; i++){ if(splitWord[i].length > longestWord) { longestWord = splitWord[i].length; } } return longestWord; } findLongestWord("The quick brown fox jumped over the lazy dog");

Where do I belong Return the lowest index at which a value (second argument) should be inserted into an array (first argument) once it has been sorted. The returned value should be a number. For example, getIndexToIns([1,2,3,4], 1.5) should return 1 because it is greater than 1 (index 0), but less than 2 (index 1). Likewise, getIndexToIns([20,3,5], 19) should return 2 because once the array has been sorted it will look like [3,5,20] and 19 is less than 20 (index 2) and greater than 5 (index 1). function getIndexToIns(arr, num) { return arr.length; } getIndexToIns([2, 5, 10], 50);

function getIndexToIns(arr,num) { arr.sort(function(a,b) { return a-b; }); for(var a = 0; a <= arr.length; a++) { if(arr[a] >= num ) return parseInt(a); } return arr.length; } getIndexToIns([2, 5, 10], 50);

Return Largest Numbers in Arrays Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays. Remember, you can iterate through an array with a simple for loop, and access each member with array syntax arr[i] function largestOfFour(arr) { // You can do this! return longestWord; } largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

function largestOfFour(arr) { var longestWord = []; for( var i = 0; i < arr.length; i++) { arr[i].sort(function(a,b) { return b-a;}); longestWord.push(arr[i][0]); } return longestWord; } largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

Mutations Return true if the string in the first element of the array contains all of the letters of the string in the second element of the array. For example, ["hello", "Hello"], should return true because all of the letters in the second string are present in the first, ignoring case. The arguments ["hello", "hey"] should return false because the string "hello" does not contain a "y". Lastly, ["Alien", "line"], should return true because all of the letters in "line" are present in "Alien". function mutation(arr) { var test = arr[1].toLowerCase(); var target = arr[0].toLowerCase(); for (i=0; i<test.length; i++) { if (target.indexOf(test[i])< 0) return false; } return true; } mutation(["hello", "hey"]);

function mutation(arr) { var test = arr[1].toLowerCase(); var target = arr[0].toLowerCase(); for(i=0; i<test.length; i++) { if(target.indexOf(text[i]) < 0) return false; } return true; } mutation(["hello","hey"]);

Map the Debris Return a new array that transforms the element's average altitude into their orbital periods. The array will contain objects in the format {name: 'name', avgAlt: avgAlt}. You can read about orbital periods on wikipedia. The values should be rounded to the nearest whole number. The body being orbited is Earth. The radius of the earth is 6367.4447 kilometers, and the GM value of earth is 398600.4418 km3s-2.

function orbitalPeriod(arr) { var GM = 398600.4418; var earthRadius = 6367.4447; var newArr = []; var op = 0; for(var i=0; i<arr.length; i++){ op = Math.round(2*Math.PI*Math.sqrt(Math.pow(earthRadius + arr[i].avgAlt,3)/GM)); nerArr.push({ name: arr[i].name, orbitalPeriod:op }); } return newArr; } orbitalPeriod([{name: "iss", avgAlt: 413.6}, {name: "hubble", avgAlt: 556.7}, {name: "moon", avgAlt: 378632.553}]);

Pairwise Given an array arr, find element pairs whose sum equal the second argument arg and return the sum of their indices. If multiple pairs are possible that have the same numeric elements but different indices, return the smallest sum of indices. Once an element has been used, it cannot be reused to pair with another. For example pairwise([7, 9, 11, 13, 15], 20) returns 6. The pairs that sum to 20 are [7, 13] and [9, 11]. We can then write out the array with their indices and values.

function pairwise(arr,arg) { if(!arr.length) return 0; var newArr = []; for(var i = 0; i<arr.length; i++){ for(var j = 0; j<arr.length; j++) { if(newArr.indexOf(i) === -1 && newArr.indexOf(j) === -1) { if(arr[i] + arr[j] === arg && i!==j) { newArr.push(i); newArr.push(j); } } } } var result = newArr.reduce(function(acc, item) { return acc+item; }); return result; } pairwise([1, 4, 2, 3, 0, 5], 7);

Return true if the given string is a palindrome. Otherwise, return false. A palindrome is a word or sentence that's spelled the same way both forward and backward, ignoring punctuation, case, and spacing. Note You'll need to remove all non-alphanumeric characters (punctuation, spaces and symbols) and turn everything lower case in order to check for palindromes. We'll pass strings with varying formats, such as "racecar", "RaceCar", and "race CAR" among others. We'll also pass strings with special symbols, such as "2A3*3a2", "2A3 3a2", and "2_A3*3#A2". function palindrome(str) { } palindrome("don");

function palindrome(str) { var re = /[\W_]/g; var lowRegStr = str.toLowerCase().replace(re, ' '); var reverseStr =lowRegStr.split('').reverse().join(''); return reverseStr === lowRegStr; } palindrome("don"); //false Regular Expressions Regular expressions are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects. These patterns are used with the exec and test methods of RegExp, and with the match, replace, search, and split methods of String. This chapter describes JavaScript regular expressions. function escapeRegExp(string) { return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string }

No repeats please Return the number of total permutations of the provided string that don't have repeated consecutive letters. Assume that all characters in the provided string are each unique. For example, aab should return 2 because it has 6 total permutations (aab, aab, aba, aba, baa, baa), but only 2 of them (aba and aba) don't have the same letter (in this case a) repeating.

function permAlone(str) { var perm = str.split(''); var newArr = []; var top; //function to swap content function swap (a,b){ top = perm[a]; perm[a] = perm[b]; perm[b] = top; } // Heap's algorithm function heap(n){ if(n === 0){ newArr.push(perm.join('')); } else{ for(var i=0; i<(n-1); i++){ heap(n-1); if (n%2 ===0){ swap(i,n-1); } else { swap(0, n-1); } } heap(n-1); } } // execute heap's algorithm heap(perm.length); //filter repeated values newArr = newArr.filter(function(val) { return !val.match(/(.)\1+/g); }); return newArr.length; } permAlone('aab');

Repeat a string repeat a string Repeat a given string (first argument) num times (second argument). Return an empty string if num is not a positive number. function repeatStringNumTimes(str, num) { } repeatStringNumTimes("abc", 3);

function repeatStringNumTimes(str,num) { if (num > 0) { return str.repeat(num); } else { return "" ; } } repeatStringNumTimes("abc", 3);

You may need to turn the string into an array before you can reverse it. Your result must be a string. function reverseString(str) { } reverseString("hello");

function reverseString(str) { return str.split(' ').reverse().join(' '); reverseString("hello");

Caesars Cipher One of the simplest and most widely known ciphers is a Caesar cipher, also known as a shift cipher. In a shift cipher the meanings of the letters are shifted by some set amount. A common modern use is the ROT13 cipher, where the values of the letters are shifted by 13 places. Thus 'A' ↔ 'N', 'B' ↔ 'O' and so on. Write a function which takes a ROT13 encoded string as input and returns a decoded string. All letters will be uppercase. Do not transform any non-alphabetic character (i.e. spaces, punctuation), but do pass them on. function rot13(str) { // LBH QVQ VG! } // Change the inputs below to test rot13("SERR PBQR PNZC");

function rot13(str) { return str.split(' ').map.call(str,function(char) { x = char.charCodeAt(0); if( x < 65 || x > 90 ) { return String.fromCharCode(x); } else if ( x < 78) { return String.fromCharCode( x +13) ; } return String.fromCharCode(x-13); }).join(' '); }

Slasher Flick Return the remaining elements of an array after chopping off n elements from the head. The head means the beginning of the array, or the zeroth index. function slasher(arr, howMany) { } slasher([1, 2, 3], 2);

function slasher(arr, howMany) { arr.splice(0,howMany); return arr; } slasher([1,2,3], 2);

Smallest Common Multiple Find the smallest common multiple of the provided parameters that can be evenly divided by both, as well as by all sequential numbers in the range between these parameters. The range will be an array of two numbers that will not necessarily be in numerical order. e.g. for 1 and 3 - find the smallest common multiple of both 1 and 3 that is evenly divisible by all numbers between 1 and 3. function smallestCommons(arr) { } smallestCommons([1,5]);

function smallestCommons(arr) { var min = Math.min(arr[0],arr[1]); var max = Math.max(arr[0],arr[1]); var result = []; for (var x=min; x<= max; x++) { result.push(x); } var a = Math.abs(result[0]); for(var j = 1; j<result.length; j++) { var b = Math.abs(result[j]); var c = a; while( a && b) { if ( a > b) { a %=b; } else { b%= a; } } a= Math.abs(c*result[j]/(a+b)); } return a; smallestCommons([1,5]);

Spinal Tap Case Convert a string to spinal case. Spinal case is all-lowercase-words-joined-by-dashes. function spinalCase(str) { } spinalCase('This Is Spinal Tap');

function spinalCase(str) { // "It's such a fine line between stupid, and clever." // --David St. Hubbins var type = str.replace(/([a-z])([A-Z])/g, '$1 $2').replace(/\s/g,'-').replace(/_/g, '-'); var code = type.toLowerCase(); return code; } spinalCase('This Is Spinal Tap');

Steamroller Flatten a nested array. You must account for varying levels of nesting. function steamrollArray(arr) { // I'm a steamroller, bab var myNewArray = []; function nestedArray(arr){ for (var i=0; i<arr.length; i++){ if(Array.isArray(arr[i])){ nestedArray(arr[i]); } else { myNewArray.push(arr[i]); } } } nestedArray(arr); return myNewArray; } steamrollArray([1, [2], [3, [[4]]]]);

function steamrollArray(arr) { var myNewArray = []; function nestedArray(arr) { // loop through the array for (var i=0; i<arr.length; i++) { // if it it array, store in nestedArray value if(Array.isArray(arr[i])){ nestedArray(arr[i]); } else { // if it is not array, push it as array to myNewArray myNewArray.push(arr[i]); } } } // store array in nestedArray nestedArray(arr); return myNewArray; } steamrollArray([1, [2], [3, [[4]]]]);

Sum All Odd Fibonacci Numbers Given a positive integer num, return the sum of all odd Fibonacci numbers that are less than or equal to num. The first two numbers in the Fibonacci sequence are 1 and 1. Every additional number in the sequence is the sum of the two previous numbers. The first six numbers of the Fibonacci sequence are 1, 1, 2, 3, 5 and 8. For example, sumFibs(10) should return 10 because all odd Fibonacci numbers less than 10 are 1, 1, 3, and 5. function sumFibs(num) { return result; } sumFibs(1);

function sumFibs(num) { var arr =[1]; for(var i=1; i<=num;) { arr.push(i); i=arr[arr.length-1] + arr[arr.length-2]; } var result = arr.reduce(function(a,b) { if(b%2 !==0) return a+b; else return a; }); return result; } sumFibs(1);

Sum All Primes Sum all the prime numbers up to and including the provided number. A prime number is defined as a number greater than one and having only two divisors, one and itself. For example, 2 is a prime number because it's only divisible by one and two. The provided number may not be a prime. function sumPrimes(num) { } sumPrimes(10);

function sumPrimes(num) { var range=[]; for(var i=2; i<= num; i++) { if(isPrimeNumer(i)) { range.push(i); } } return range.reduce(function(a,b) { return a+b; }); } function isPrimeNumber(num) { for(var j=2; j<num; j++) { if(num%j ===0 ) { return false; } } return true; } sumPrimes(10);

Symmetric Difference Given two sets (for example set A = {1, 2, 3} and set B = {2, 3, 4}), the mathematical term "symmetric difference" of two sets is the set of elements which are in either of the two sets, but not in both (A △ B = C = {1, 4}). For every additional symmetric difference you take (say on a set D = {2, 3}), you should get the set with elements which are in either of the two the sets but not both (C △ D = {1, 4} △ {2, 3} = {1, 2, 3, 4}). function sym(args) { return args; } sym([1, 2, 3], [5, 2, 1, 4]);

function sym() { //convert the arguments object into a proper array var args = Array.prototype.slice.call(arguments); // Return the symmetric difference of 2 arrays var getDiff = function(arr1, arr2){ //return items in arr1 that don't exist in arr2 function filterFunction(arr1,arr2){ return arr1.filter(function(item){ return arr2.indexOf(item) ===-1; }); } // Run filter function on each array against the other return filterFunction(arr1, arr2).concat(filterFunction(arr2,arr1)); }; //Reduce all arguments getting the difference of them var symarry = args.reduce(getDiff, []); //run filter function to get the unique values var unique = symarray.filter(function(elem, index, self) { return index === self.indexOf(elem); }); return unique; } // test here sym([1, 2, 3], [5, 2, 1, 4]);

Return the provided string with the first letter of each word capitalized. Make sure the rest of the word is in lower case. For the purpose of this exercise, you should also capitalize connecting words like "the" and "of". function titleCase(str) { } titleCase("I'm a little tea pot");

function titleCase(str) { str = str.toLowerCase().split(' '); for (var i = 0; i < str.length; i ++){ str[i] = str[i].charAt(0).toUppderCase() + str[i].slice(1); } return str.join(' '); titleCase("I'm a little tea pot");

Title Case a Sentence Return the provided string with the first letter of each word capitalized. Make sure the rest of the word is in lower case. For the purpose of this exercise, you should also capitalize connecting words like "the" and "of". function titleCase(str) { } titleCase("I'm a little tea pot");

function titleCase(str){ str = str.toLowerCase().split(' '); for(var i=0; i<str.length; i++){ str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1); } return str.join(' '); } titleCase('I'm a little tea pot');

Truncate a string Truncate a string (first argument) if it is longer than the given maximum string length (second argument). Return the truncated string with a ... ending. Note that inserting the three dots to the end will add to the string length. However, if the given maximum string length num is less than or equal to 3, then the addition of the three dots does not add to the string length in determining the truncated string. function truncateString(str, num) { } truncateString("A-tisket a-tasket A green and yellow basket", 50);

function truncateString(str, num) { if(str.length > num && num > 3) { return str.slice (0, (num -3)) + '...'; } else if (str.length > num && num <= 3) { return str.slice(0, num) + '...'; } else { return str; } } truncateString("A-tisket a-tasket A green and yellow basket", 50);

Everything Be True Check if the predicate (second argument) is truthy on all elements of a collection (first argument). Remember, you can access object properties through either dot notation or [] notation. function truthCheck(collection, pre) { } truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex");

function truthCheck(collection,pre) { for(var i=0; i<collection.length; i++) { if(!collection[i][pre]) { return false; } } return true; } truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex"); function truthCheck(collection,pre){ return collection.every(function (element){ return element.hasOwnProperty(pre) && Boolean(element[pre]); }); }

Sorted Union Write a function that takes two or more arrays and returns a new array of unique values in the order of the original provided arrays. In other words, all values present from all arrays should be included in their original order, but with no duplicates in the final array. The unique numbers should be sorted by their original order, but the final array should not be sorted in numerical order. function uniteUnique(arr) { } } } return result; } uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);

function uniteUnique(arr) { var result = []; for(var i=0; i<arguments.length; i++) { for(var j=0; j<arguments.length; j++) { if(result.indexOf(arguments[i][j] < 0) { retult.push(arguments[i][j]); } } } return result; } uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);

Inventory Update Compare and update the inventory stored in a 2D array against a second 2D array of a fresh delivery. Update the current existing inventory item quantities (in arr1). If an item cannot be found, add the new item and quantity into the inventory array. The returned inventory array should be in alphabetical order by item.

function updateInventory(arr1, arr2) { var inventory = arr1.concat(arr2).reduce(function(acc, next) { if(acc[next[1]]) { acc[next[1]] += next[0]; } else { acc[next[1] = next[0]; } return acc; },{}); return Object.keys(inventory).map(function(value) { return [inventory[value],value]; }).sort(function(a,b){ return a[1]>b[1]; }); } // Example inventory lists var curInv = [ [21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"] ]; var newInv = [ [2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"] ]; updateInventory(curInv, newInv);

Wherefore art thou Make a function that looks through an array of objects (first argument) and returns an array of all objects that have matching property and value pairs (second argument). Each property and value pair of the source object has to be present in the object from the collection if it is to be included in the returned array. For example, if the first argument is [{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], and the second argument is { last: "Capulet" }, then you must return the third object from the array (the first argument), because it contains the property and its value, that was passed on as the second argument.

function whatIsInAName(collection, source) { // What's in a name? // Only change code below this line var key = Object.keys(source); var arr = collection.filter(function(obj){ for (var i=0; i < key.length; i++) { if (!obj.hasOwnProperty(key[i]) || obj[key[i]] !== source[key[i]]){ return false; } } return true; }); return arr; } whatIsInAName([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 }); print out function whatIsInAName(collection, source) { // What's in a name? // Only change code below this line var key = Object.keys(source); var arr = collection.filter(function(obj){ for (var i=0; i < key.length; i++) { if (!obj.hasOwnProperty(key[i]) || obj[key[i]] !== source[key[i]]){ return false; } } return true; }); return arr; } whatIsInAName([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 });


Set pelajaran terkait

Personal Finance Chapter 2 - Money Management Skills

View Set

Physical Sensation Words (You can use these words to communicate with your limbic system. ^^)

View Set

CMU CPS 181 - Chapter 10 Review Questions

View Set