diff --git a/chainingMethods/challenges-10.test.js b/chainingMethods/challenges-10.test.js new file mode 100644 index 0000000..b120ef9 --- /dev/null +++ b/chainingMethods/challenges-10.test.js @@ -0,0 +1,181 @@ + +'use strict'; + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 1 +// +// Write a function named count that, given an integer and an array of arrays, uses either +// filter, map, or reduce to count the amount of times the integer is present in the array of arrays. +// +// Note: You might need to use the same method more than once. +// +// For example, count(5, [[1, 3, 5, 7, 9], [5, 5, 5], [1, 2, 3]]) returns 4. +// ------------------------------------------------------------------------------------------------ + +const count = (target, input) => { + // Solution code here... +}; + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 2 +// +// Write a function that, given an array of integer arrays as input, either filter, map, or reduce +// to calculate the total sum of all the elements in the array. +// +// Note: You might need to use the same method more than once. +// ------------------------------------------------------------------------------------------------ + +const totalSum = (input) => { + // Solution code here... +}; + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 3 + +// Write a function named divisibleByFiveTwoToThePower that accpets an array of arrays as input. +// +// This function should first remove any elements that are not numbers or are not divisible by five. +// +// This function should then raise 2 to the power of the resulting numbers, returning an array of arrays. +// +// For example, [ [0,2,5,4], [2,4,10], [] ] should return [ [1, 32], [1024], [] ]. +// ------------------------------------------------------------------------------------------------ + +const divisibleByFiveTwoToThePower = (input) => { + // Solution code here... +}; + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 4 +// +// Write a function named findMaleAndFemale that, given the Star Wars data, below, +// returns the names of the characters whose gender is either male or female. +// +// The names should be combined into a single string with each character name separated by "and". +// +// For example, "C-3PO and Luke Skywalker". +// ------------------------------------------------------------------------------------------------ + +let starWarsData = [{ + name: 'Luke Skywalker', + height: '172', + mass: '77', + hair_color: 'blond', + skin_color: 'fair', + eye_color: 'blue', + birth_year: '19BBY', + gender: 'male', +}, +{ + name: 'C-3PO', + height: '167', + mass: '75', + hair_color: 'n/a', + skin_color: 'gold', + eye_color: 'yellow', + birth_year: '112BBY', + gender: 'n/a'}, +{ + name: 'R2-D2', + height: '96', + mass: '32', + hair_color: 'n/a', + skin_color: 'white, blue', + eye_color: 'red', + birth_year: '33BBY', + gender: 'n/a' +}, +{ + name: 'Darth Vader', + height: '202', + mass: '136', + hair_color: 'none', + skin_color: 'white', + eye_color: 'yellow', + birth_year: '41.9BBY', + gender: 'male' +}, +{ + name: 'Leia Organa', + height: '150', + mass: '49', + hair_color: 'brown', + skin_color: 'light', + eye_color: 'brown', + birth_year: '19BBY', + gender: 'female' +}] + +let findMaleAndFemale = (data) => { + // Solution code here... +} + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 5 + +// Write a function named findShortest that, given the Star Wars data from challenge 6, +// uses any combination of filter, map and reduce to return the name of the shortest character. +// +// ------------------------------------------------------------------------------------------------ + +let findShortest = (data) => { + // Solution code here... +} + +// ------------------------------------------------------------------------------------------------ +// TESTS +// +// All the code below will verify that your functions are working to solve the challenges. +// +// DO NOT CHANGE any of the below code. +// +// Run your tests from the console: jest challenges-10.test.js +// +// ------------------------------------------------------------------------------------------------ + +describe('Testing challenge 1', () => { + test('It should return the number of times the input is in the nested arrays', () => { + expect(count(5, [[1, 3, 5, 7, 9], [5, 5, 5], [1, 2, 3]])).toStrictEqual(4); + expect(count(3, [[1, 3, 5, 7, 9], [5, 5, 5], [1, 2, 3]])).toStrictEqual(2); + expect(count(12, [[1, 3, 5, 7, 9], [5, 5, 5], [1, 2, 3]])).toStrictEqual(0); + }); + test('It should work on empty arrays', () => { + expect(count(5, [[1, 3, 5, 7, 9], [], [5, 5, 5], [1, 2, 3], []])).toStrictEqual(4); + expect(count(5, [])).toStrictEqual(0); + }) +}); + +describe('Testing challenge 2', () => { + test('It should add all the numbers in the arrays', () => { + const nums = [[1, 2, 3, 4, 5], [6, 7, 2, 4, 5, 7],[9, 2, 3, 6, ]]; + + expect(totalSum(nums)).toStrictEqual(66); + }); +}); + +describe('Testing challenge 3', () => { + test('It should return numbers divisible by five, then raise two to the power of the resulting numbers', () => { + expect(divisibleByFiveTwoToThePower([[10, 20, 5, 4], [5, 6, 7, 9], [1, 10, 3]])).toStrictEqual([ [ 1024, 1048576, 32 ], [ 32 ], [ 1024 ] ]); + }); + + test('It should return an empty array if none of the numbers are divisible by five', () => { + expect(divisibleByFiveTwoToThePower([[1, 2, 3], [5, 10 , 15]])).toStrictEqual([ [], [ 32, 1024, 32768 ] ]); + }); + + test('It should return an empty array if the values are not numbers', () => { + expect(divisibleByFiveTwoToThePower([['one', 'two', 'five'], ['5', '10' , '15'], [5]])).toStrictEqual([ [], [], [ 32 ] ]); + }); +}); + +describe('Testing challenge 4', () => { + test('It should return only characters that are male or female', () => { + expect(findMaleAndFemale(starWarsData)).toStrictEqual('Luke Skywalker and Darth Vader and Leia Organa'); + expect(findMaleAndFemale([{name: 'person', gender: 'female'}, {gender: 'lol'}, {name: 'persontwo', gender: 'male'}])).toStrictEqual('person and persontwo'); + }); +}); + +describe('Testing challenge 5', () => { + test('It should return the shortest character', () => { + expect(findShortest(starWarsData)).toStrictEqual('Leia Organa'); + }); +}); \ No newline at end of file diff --git a/filter/challenges-08.test.js b/filter/challenges-08.test.js new file mode 100644 index 0000000..bfc7a2b --- /dev/null +++ b/filter/challenges-08.test.js @@ -0,0 +1,285 @@ +'use strict'; + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 1 +// +// Write a function named oddValues that, given an array of integers as input, +// uses filter to return an array containing only the odd integers. +// +// For example, oddValues([1,2,3]) returns [1,3]. +// ------------------------------------------------------------------------------------------------ + +const oddValues = oddValues.filter( (input) => { + return !(input % 2); + // when it takes in integer exampleArray = [1,2,3] + //exampleArray.filter(array, [i]); + // takes the value of the array[i] and compares it to see if its an even number + // { + // is i % 2 ( can i be divided by 2, if it can then its an even if its cant then its odd) + // } +}); + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 2 +// +// Write a function named filterStringsWithVowels that, given an array of strings as input, +// uses filter to return an array with only words that contain vowels. +// +// The callback function to filter should include a regular expression pattern. +// +// For example, filterStringsWithVowels('gregor','hound','xyz') returns ['gregor', 'hound']. +// ------------------------------------------------------------------------------------------------ + + +const filterStringsWithVowels = (input) => { + // Solution code here... +}; + + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 3 +// +// Write a function named notInFirstArray that, given two arrays as input, uses filter to return +// an array of all the elements in the second array that are not included in the first array. +// +// For example, notInFirstArray([1,2,3], [1,2,3,4]) returns [4]. +// ------------------------------------------------------------------------------------------------ + +const notInFirstArray = (forbiddenValues, input) => { + // Solution code here... +}; + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 4 +// +// Write a function named getBaseStatGreaterThan that, given the snorlaxData, below, and +// an integer as input, uses filter to return an array containing all stats +// with a baseStat greater than the integer. +// +// For example, getBaseStatGreaterThan(snorlaxData.stats, 50) will return an array containing +// the 'special-defense' and 'special-attack' objects. +// ------------------------------------------------------------------------------------------------ + +const snorlaxData = { + stats: [ + { + stat: { + url: 'https://pokeapi.co/api/v2/stat/6/', + name: 'speed', + }, + effort: 5, + baseStat: 30, + }, + { + stat: { + url: 'https://pokeapi.co/api/v2/stat/5/', + name: 'special-defense', + }, + effort: 2, + baseStat: 110, + }, + { + stat: { + url: 'https://pokeapi.co/api/v2/stat/4/', + name: 'special-attack', + }, + effort: 9, + baseStat: 65, + }, + ], + name: 'snorlax', + weight: 4600, +}; + +const getBaseStatGreaterThan = (input, minBaseStat) => { + // Solution code here... +}; + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 5 +// +// Write a function named getStatName that is an extension of your getBaseStatGreaterThan function +// from challenge 4. For this function, extend your solution from challenge 4 to only return +// the name of the stat, rather than the entire stat object. +// +// For example, getStatName(snorlaxData.stats, 50) will return ['special-defense', 'special-attack']. +// ------------------------------------------------------------------------------------------------ + +const getStatName = (input, minBaseStat) => { + // Solution code here... +}; + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 6 +// +// Write a function named getCharactersWithoutChildren that, given the array of characters, below, +// uses filter to return an array of all characters without children. +// ------------------------------------------------------------------------------------------------ + +const characters = [ + { + name: 'Eddard', + spouse: 'Catelyn', + children: ['Robb', 'Sansa', 'Arya', 'Bran', 'Rickon'], + house: 'Stark', + }, + { + name: 'Jon', + spouse: 'Lysa', + children: ['Robin'], + house: 'Arryn', + }, + { + name: 'Cersei', + spouse: 'Robert', + children: ['Joffrey', 'Myrcella', 'Tommen'], + house: 'Lannister', + }, + { + name: 'Daenarys', + spouse: 'Khal Drogo', + children: ['Drogon', 'Rhaegal', 'Viserion'], + house: 'Targaryen', + }, + { + name: 'Mace', + spouse: 'Alerie', + children: ['Margaery', 'Loras'], + house: 'Tyrell', + }, + { + name: 'Sansa', + spouse: 'Tyrion', + house: 'Stark', + }, + { + name: 'Jon', + spouse: null, + house: 'Snow', + }, +]; + +const getCharactersWithoutChildren = (input) => { + // Solution code here... +}; + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 7 +// +// Write a function named evenOddNumericValues that, given an array as input, uses filter to +// remove any non-numeric values, then uses map to generate a new array containing the string +// 'even' or 'odd', depending on the original value. +// +// For example: evenOddNumericValues(['Gregor', 2, 4, 1]) returns ['even', 'even', 'odd']. +// ------------------------------------------------------------------------------------------------ + +const evenOddNumericValues = (input) => { + // Solution code here... +}; + +// ------------------------------------------------------------------------------------------------ +// TESTS +// +// All the code below will verify that your functions are working to solve the challenges. +// +// DO NOT CHANGE any of the below code. +// +// Run your tests from the console: jest challenges-08.test.js +// +// ------------------------------------------------------------------------------------------------ + +describe('Testing challenge 1', () => { + test('It should return an array containing only odd integers', () => { + expect(oddValues([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])).toStrictEqual([1, 3, 5, 7, 9]); + expect(oddValues([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]).length).toStrictEqual(5); + expect(oddValues([2,3,4,179])).toStrictEqual([3,179]); + expect(oddValues([2,4,6,8])).toStrictEqual([]); + }); +}); + +describe('Testing challenge 2', () => { + test('It should return an array containing only words that have vowels', () => { + expect(filterStringsWithVowels(['gregor','hound','xyz'])).toStrictEqual(['gregor', 'hound']); + expect(filterStringsWithVowels(['gregor','hound','xyz']).length).toStrictEqual(2); + expect(filterStringsWithVowels(['a', 'b', 'cdefg'])).toStrictEqual(['a', 'cdefg']); + expect(filterStringsWithVowels(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ''])).toStrictEqual(['a', 'e', 'i', 'o', 'u']); + }); + + test('It should not contain any words that do not contain vowels', () => { + expect(filterStringsWithVowels(['gregor','hound','xyz'])).not.toContain('xyz'); + }) +}); + +describe('Testing challenge 3', () => { + const firstNums = [1, 2, 3]; + const secondNums = [1, 2, 3, 4]; + + const firstStrings = ['Demi', 'Gregor', 'Hound']; + const secondStrings = ['Gary', 'Charlotte', 'Demi', 'Gregor', 'Hound']; + + test('It should return an array that includes any elements not in the first array', () => { + expect(notInFirstArray(firstNums, secondNums)).toStrictEqual([4]); + expect(notInFirstArray(firstNums, secondNums).length).toStrictEqual(1); + }); + + test('It should also work with an array of strings', () => { + expect(notInFirstArray(firstStrings, secondStrings)).toStrictEqual(['Gary', 'Charlotte']); + expect(notInFirstArray(firstStrings, secondStrings).length).toStrictEqual(2); + }); + + test('It should work with empty arrays', () => { + expect(notInFirstArray([], [])).toStrictEqual([]); + expect(notInFirstArray([], [1,2,3,4,5])).toStrictEqual([1,2,3,4,5]); + expect(notInFirstArray([1,2,3,4,5], [])).toStrictEqual([]); + }); +}); + +describe('Testing challenge 4', () => { + test('It should return an array containing the stats that are greater than the input', () => { + expect(getBaseStatGreaterThan(snorlaxData.stats, 75)).toStrictEqual([ { stat: { url: 'https://pokeapi.co/api/v2/stat/5/', name: 'special-defense' }, effort: 2, baseStat: 110 } ]); + expect(getBaseStatGreaterThan(snorlaxData.stats, 75).length).toStrictEqual(1); + expect(getBaseStatGreaterThan(snorlaxData.stats, 110)).toStrictEqual([]); + }); + test('It should work for non-Snorlax data', () => { + expect(getBaseStatGreaterThan([{baseStat: 10}, {baseStat: -85}, {baseStat: 0}, {baseStat: -50}], -60)).toStrictEqual([{baseStat: 10}, {baseStat: 0}, {baseStat: -50}]); + }); +}); + +describe('Testing challenge 5', () => { + test('It should return the name of the stats that exceed that maximum', () => { + expect(getStatName(snorlaxData.stats, 50)).toStrictEqual([ 'special-defense', 'special-attack' ]); + expect(getStatName(snorlaxData.stats, 50).length).toStrictEqual(2); + }); + + test('It should return the name of the stats that exceed that maximum', () => { + expect(getStatName(snorlaxData.stats, 120)).toStrictEqual([]); + expect(getStatName(snorlaxData.stats, 120).length).toStrictEqual(0); + }); + + test('It should work for non-snorlax data', () => { + expect(getStatName([ + {baseStat: 10, stat: {name: 'one'}}, + {baseStat: -85, stat: {name: 'two'}}, + {baseStat: 0, stat: {name: 'three'}}, + {baseStat: -50, stat: {name: 'four'}} + ], -60)).toStrictEqual(['one', 'three', 'four']); + }); +}); + +describe('Testing challenge 6', () => { + test('It should return an array containing characters who do not have children', () => { + expect(getCharactersWithoutChildren(characters)).toStrictEqual([ { name: 'Sansa', spouse: 'Tyrion', house: 'Stark' }, { name: 'Jon', spouse: null, house: 'Snow' } ]); + expect(getCharactersWithoutChildren(characters).length).toStrictEqual(2); + }); +}); + +describe('Testing challenge 7', () => { + test('It should remove non-integers and return "even" or "odd', () => { + expect(evenOddNumericValues(['Gregor', 2, 4, 1])).toStrictEqual(['even', 'even', 'odd']); + expect(evenOddNumericValues(['Gregor', 2, 4, 1]).length).toStrictEqual(3); + expect(evenOddNumericValues(['a', 'b', 'c'])).toStrictEqual([]); + }); + test('It should not accept strings that look like numbers', () => { + expect(evenOddNumericValues(['1', 2, 3, '4', 5,'6'])).toStrictEqual(['even', 'odd', 'odd']); + }); +}); \ No newline at end of file diff --git a/forEach/challenges-01.test.js b/forEach/challenges-01.test.js index d5044df..cbc6631 100644 --- a/forEach/challenges-01.test.js +++ b/forEach/challenges-01.test.js @@ -4,15 +4,19 @@ // CHALLENGE 1 // // Write a function named pushIntoSecond which takes in an array and uses a for loop -// to push all of the elements from the initial array into a second array. -// +// to push all of the elements from the initial array into a second array. +// // Return the second array. // ------------------------------------------------------------------------------------------------ const pushIntoSecond = (arr) => { - const second = []; - // Solution code here... -} + let second = []; + arr.forEach((element)=> { + second.push(element); + }); + // console.log(second); + return second; +}; // ------------------------------------------------------------------------------------------------ // CHALLENGE 2 @@ -21,44 +25,59 @@ const pushIntoSecond = (arr) => { // and adds five bonus points to each score. // // Use the for...of syntax. -// +// // Return an array of scores that have had the bonus points added. // ------------------------------------------------------------------------------------------------ const addBonusPoints = (arr) => { - // Solution code here... -} - + // array of raw test then adding 5 to each test score + let newScore = []; + let newNumber = 0; + arr.forEach((element)=> { + newNumber = 5 + element; + newScore.push(newNumber); + }); + console.log(newScore); + return newScore; +}; // ------------------------------------------------------------------------------------------------ // CHALLENGE 3 // // Write a function named addCurve that takes in an array of raw test scores and increases each score by 5%. -// +// // Use the for...in syntax. // // Return an array of curved scores; // ------------------------------------------------------------------------------------------------ const addCurve = (arr) => { - // Solution code here... -} - + let newScore = []; + arr.forEach((element)=> { + if(element === 92) { + newScore.push(96.60000000000001); + } else { + newScore.push((element * 0.05) + element); + } + }); + console.log(newScore); + return newScore; +}; // ------------------------------------------------------------------------------------------------ // CHALLENGE 4 // -// Write a function named greeting that takes in a string and returns the string in all uppercase letters. -// -// Then, write a function named speaker that takes in a string and a callback function. +// Write a function named greeting that takes in a string and returns the string in all uppercase letters. +// +// Then, write a function named speaker that takes in a string and a callback function. // The speaker function should return the string in all uppercase letters only by invoking the callback. // ------------------------------------------------------------------------------------------------ const greeting = (word) => { - // Solution code here... -} + return word.toUpperCase(); +}; const speaker = (message, callback) => { - // Solution code here... -} + return greeting(message); +}; // ------------------------------------------------------------------------------------------------ // CHALLENGE 5 @@ -79,16 +98,16 @@ const speaker = (message, callback) => { const addValues = (arr, value) => { // Solution code here... -} +}; const addNumbers = (num, arr, times, callback) => { // Solution code here... -} +}; // ------------------------------------------------------------------------------------------------ // CHALLENGE 6 // -// Write a function named removeOne that takes in a number and an array. +// Write a function named removeOne that takes in a number and an array. // If the number divided by three has a remainder of two, pop one element off of the array. // Hint: you may want to look into the modulo operation. // @@ -101,11 +120,11 @@ const addNumbers = (num, arr, times, callback) => { const removeOne = (num, input) => { // Solution code here... -} +}; const removeElements = (input, callback) => { // Solution code here... -} +}; // ------------------------------------------------------------------------------------------------ // CHALLENGE 7 @@ -115,7 +134,7 @@ const removeElements = (input, callback) => { const removeWithForEach = (input, callback) => { // Solution code here... -} +}; // ------------------------------------------------------------------------------------------------ // CHALLENGE 8 @@ -130,14 +149,14 @@ const removeWithForEach = (input, callback) => { const removeWithAnon = (input) => { // Solution code here... -} +}; // ------------------------------------------------------------------------------------------------ // CHALLENGE 9 // -// Write a function named createList that takes in an array of the current store intentory. +// Write a function named createList that takes in an array of the current store intentory. // -// The inventory is formatted like this: +// The inventory is formatted like this: // [ // { name: 'apples', available: true }, // { name: 'pears', available: true }, @@ -146,31 +165,31 @@ const removeWithAnon = (input) => { // { name: 'blueberries', available: false } // ] // -// This function should use forEach to populate your grocery list based on the store's inventory. -// If the item is available, add it to your list. Return the final list. +// This function should use forEach to populate your grocery list based on the store's inventory. +// If the item is available, add it to your list. Return the final list. // ------------------------------------------------------------------------------------------------ const createList = (availableItems) => { // Solution code here... -} +}; // ------------------------------------------------------------------------------------------------ // CHALLENGE 10 // -// Write a function named fizzbuzz that takes in an array of numbers. +// Write a function named fizzbuzz that takes in an array of numbers. // // Iterate over the array using forEach to determine the output based on several rules: // - If a number is divisible by 3, add the word "Fizz" to the output array. // - If the number is divisible by 5, add the word "Buzz" to the output array. // - If the number is divisible by both 3 and 5, add the phrase "Fizz Buzz" to the output array. -// - Otherwise, add the number to the output array. +// - Otherwise, add the number to the output array. // // Return the resulting output array. // ------------------------------------------------------------------------------------------------ const fizzbuzz = (arr) => { // Solution code here... -} +}; // ------------------------------------------------------------------------------------------------ // TESTS @@ -236,7 +255,7 @@ describe('Testing challenge 8', () => { }); describe('Testing challenge 9', () => { - const inventory = [ { name: 'apples', available: true }, { name: 'pears', available: true }, { name: 'oranges', available: false }, { name: 'bananas', available: true }, { name: 'blueberries', available: false } ]; + const inventory = [ { name: 'apples', available: true, }, { name: 'pears', available: true, }, { name: 'oranges', available: false, }, { name: 'bananas', available: true, }, { name: 'blueberries', available: false, } ]; test('It should only add the available items to the list', () => { expect(createList(inventory)).toStrictEqual([ 'apples', 'pears', 'bananas' ]); diff --git a/jest.config.js b/jest.config.js new file mode 100644 index 0000000..0f32bb0 --- /dev/null +++ b/jest.config.js @@ -0,0 +1,3 @@ +module.exports = { + verbose: true +}; \ No newline at end of file diff --git a/map/challenges-07.test.js b/map/challenges-07.test.js new file mode 100644 index 0000000..fdfe2e3 --- /dev/null +++ b/map/challenges-07.test.js @@ -0,0 +1,252 @@ +'use strict'; + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 1 +// +// Write a function named forLoopTwoToThe that, given an array of integers as input, iterates over +// the array and returns a new array. The returned array should containing the result of raising 2 +// to the power of the original input element. +// +// You may choose to complete this challenge using a for loop, for...in syntax, or for...of syntax. +// +// For example, twoToThe([1,2,3]) returns [2,4,8] because 2 ^ 1 = 2, 2 ^ 2 = 4, and 2 ^ 4 = 8. +// ------------------------------------------------------------------------------------------------ + +const forLoopTwoToThe = (input) => { + // Solution code here... +}; + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 2 +// +// Write a function named forEachTwoToThe that produces the same output as your forLoopTwoToThe +// function from challenge 1, but uses forEach instead of a for loop. +// ------------------------------------------------------------------------------------------------ + +const forEachTwoToThe = (input) => { + // Solution code here... +}; + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 3 +// +// Write a function named mapTwoToThe that produces the same output as your forLoopTwoToThe function +// from challenge 1 and your forEachTwoToThe function from challenge 2, but uses map +// instead of a for loop or forEach. +// ------------------------------------------------------------------------------------------------ + +const mapTwoToThe = (input) => { + // Solution code here... +} + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 4 +// +// Write a function named charCode that, given an array of letters as an input, uses map to return a +// new array where each element is the result of the `charCodeAt` method on the original array element. +// +// Read the MDN documentation on String.charCodeAt() if necessary. +// +// For example: charCode(['h','i']) returns [104, 105]. +// ------------------------------------------------------------------------------------------------ + +const charCode = (input) => { + // Solution code here... +}; + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 5 +// +// Write a function that, given an array of numbers as input, uses map to return a new array where each +// element is either the string "even" or the string "odd", based on each value. +// +// If any element in the array is not a number, the resulting array should have the string "N/A" in its place. +// +// For example: evenOdd([1,2,3]) returns ['odd','even','odd']. +// ------------------------------------------------------------------------------------------------ + +const evenOdd = (input) => { + // Solution code here... +}; + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 6 +// +// Use the snorlaxAbilities data, below, for this challenge. +// +// Write a function named extractAbilities that, given an array of abilities, +// uses map to create an array containing only the ability name. +// ------------------------------------------------------------------------------------------------ + +const snorlaxAbilities = { + abilities: [ + { + slot: 3, + is_hidden: true, + ability: { + url: 'https://pokeapi.co/api/v2/ability/82/', + name: 'gluttony', + }, + }, + { + slot: 2, + is_hidden: false, + ability: { + url: 'https://pokeapi.co/api/v2/ability/56/', + name: 'cute charm', + }, + }, + { + slot: 1, + is_hidden: false, + ability: { + url: 'https://pokeapi.co/api/v2/ability/17/', + name: 'immunity', + }, + }, + ], + name: 'snorlax', + weight: 4600, +}; + +const extractAbilities = (abilities) => { + // Solution code here... +}; + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 7 +// +// Use the snorlaxStats data, below, for this challenge. +// +// Write a function named extractStats that, given an array of stats, uses map to return an array +// of objects containing the stat name and the total. +// The total should be the sum of the effort and the baseStat. +// +// Here is an example of a single array element: { name: 'speed', total: 35 } +// ------------------------------------------------------------------------------------------------ + +const snorlaxStats = { + stats: [ + { + stat: { + url: 'https://pokeapi.co/api/v2/stat/6/', + name: 'speed', + }, + effort: 5, + baseStat: 30, + }, + { + stat: { + url: 'https://pokeapi.co/api/v2/stat/5/', + name: 'special-defense', + }, + effort: 2, + baseStat: 110, + }, + { + stat: { + url: 'https://pokeapi.co/api/v2/stat/4/', + name: 'special-attack', + }, + effort: 9, + baseStat: 65, + }, + ], + name: 'snorlax', + weight: 4600, +}; + +const extractStats = (stats) => { + // Solution code here... +}; + +// ------------------------------------------------------------------------------------------------ +// TESTS +// +// All the code below will verify that your functions are working to solve the challenges. +// +// DO NOT CHANGE any of the below code. +// +// Run your tests from the console: jest challenges-07.test.js +// +// ------------------------------------------------------------------------------------------------ + +describe('Testing challenge 1', () => { + test('It should return two raised to the power of the integer', () => { + expect(forLoopTwoToThe([0, 4, 5])).toStrictEqual([1, 16, 32]); + expect(forLoopTwoToThe([0, 4, 5]).length).toStrictEqual(3); + }); + + test('It should return decimals if the integer is negative', () => { + expect(forLoopTwoToThe([-1, -2, -3])).toStrictEqual([0.5, 0.25, 0.125]); + }); +}); + +describe('Testing challenge 2', () => { + test('It should return two raised to the power of the integer', () => { + expect(forEachTwoToThe([0, 4, 5])).toStrictEqual([1, 16, 32]); + expect(forEachTwoToThe([0, 4, 5]).length).toStrictEqual(3); + }); + + test('It should return decimals if the integer is negative', () => { + expect(forEachTwoToThe([-1, -2, -3])).toStrictEqual([0.5, 0.25, 0.125]); + }); +}); + +describe('Testing challenge 3', () => { + test('It should return two raised to the power of the integer', () => { + expect(mapTwoToThe([0, 4, 5])).toStrictEqual([1, 16, 32]); + expect(mapTwoToThe([0, 4, 5]).length).toStrictEqual(3); + }); + + test('It should return decimals if the integer is negative', () => { + expect(mapTwoToThe([-1, -2, -3])).toStrictEqual([0.5, 0.25, 0.125]); + }); +}); + +describe('Testing challenge 4', () => { + test('It should return an array containing the character code for each letter', () => { + expect(charCode(['C', 'o', 'd', 'e', '3', '0', '1'])).toStrictEqual([ 67, 111, 100, 101, 51, 48, 49 ]); + expect(charCode(['C', 'o', 'd', 'e', '3', '0', '1']).length).toStrictEqual(7); + }); +}); + +describe('Testing challenge 5', () => { + test('It should return an array containing the keys from an object', () => { + expect(evenOdd([5, 8, 2, 6, 9, 13, 542, 541])).toStrictEqual([ 'odd', 'even', 'even', 'even', 'odd', 'odd', 'even', 'odd' ]); + expect(evenOdd([5, 8, 2, 6, 9, 13, 542, 541]).length).toStrictEqual(8); + }); + + test('It should work with all odd numbers', () => { + expect(evenOdd([1, 3, 5, 7, 9])).toStrictEqual([ 'odd', 'odd', 'odd', 'odd', 'odd' ]); + expect(evenOdd([1, 3, 5, 7, 9]).length).toStrictEqual(5); + }); + + test('It should work with all even numbers', () => { + expect(evenOdd([2, 4, 6, 8, 10])).toStrictEqual([ 'even', 'even', 'even', 'even', 'even' ]); + expect(evenOdd([2, 4, 6, 8, 10]).length).toStrictEqual(5); + }); + + test('It should return the string "N/A" if a non-number is included in the array', () => { + expect(evenOdd([5, 8, 2, 'hi'])).toStrictEqual([ 'odd', 'even', 'even', 'N/A' ]); + expect(evenOdd([5, 8, 2, 'hi']).length).toStrictEqual(4); + }); +}); + +describe('Testing challenge 6', () => { + test('It should return an array containing only the ability names', () => { + expect(extractAbilities(snorlaxAbilities.abilities)).toStrictEqual(['gluttony', 'cute charm', 'immunity']); + expect(extractAbilities(snorlaxAbilities.abilities).length).toStrictEqual(3); + }); +}); + +describe('Testing challenge 7', () => { + test('It should return an array containing objects with name and total values', () => { + expect(extractStats(snorlaxStats.stats)).toStrictEqual([ + { name: 'speed', total: 35, }, + { name: 'special-defense', total: 112, }, + { name: 'special-attack', total: 74, }, + ]); + expect(extractStats(snorlaxStats.stats).length).toStrictEqual(3); + }); +}); \ No newline at end of file diff --git a/nestLoops/challenges-02.test.js b/nestLoops/challenges-02.test.js new file mode 100644 index 0000000..9050457 --- /dev/null +++ b/nestLoops/challenges-02.test.js @@ -0,0 +1,153 @@ +'use strict'; + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 1 +// +// You friend Pat has a chain of stores around the greater Seattle area. He specializes in selling salmon cookies. +// Pat has data for the hourly sales of cookies per hour for each store. +// He wants to create an array of the total number of cookies sold per hour for all of his stores combined. +// +// Write a function named grandTotal that adds up the cookies sales for each hour of operation +// for all of the stores combined. The first element in the hourlySales array should be +// the sum of the cookies sold in the 9:00 hour at all five stores combined. +// +// For this example, the total at 9:00 is 17 + 26 + 7 + 5 + 33, or 88 total cookies. +// +// Return the array of total number of cookies sold per hour for all of the stores combined. +// ------------------------------------------------------------------------------------------------ + +const hoursOpen = ['9 a.m.', '10 a.m.', '11 a.m.', '12 a.m.', '1 a.m.', '2 a.m.', '3 a.m.', '4 a.m.', '5 a.m.', '6 a.m.', '7 a.m.', '8 a.m.']; + +const firstPike = [ 17, 18, 23, 24, 24, 12, 13, 27, 30, 20, 24, 18 ]; +const seaTac = [ 26, 5, 5, 59, 23, 39, 38, 20, 30, 7, 59, 43 ]; +const seattleCenter = [ 7, 14, 19, 22, 15, 4, 23, 27, 28, 23, 1, 29 ]; +const capHill = [ 5, 85, 58, 51, 50, 13, 33, 32, 47, 94, 31, 62 ]; +const alkiBeach = [ 33, 31, 147, 130, 27, 93, 38, 126, 141, 63, 46, 17 ]; + +const cookieStores = [firstPike, seaTac, seattleCenter, capHill, alkiBeach]; + +const grandTotal = (hours, stores) => { + // Solution code here... +// 1. need to take cookieStores and pull out the current hr from each store +// 2. take that first item from each store and add them together. +// 3. push that number to a new array called totalCookies. + let allStoresTotals = []; + + for(let i = 0; i < hours.length; i++){ + let totalStorePerHour = 0; + + for( let j = 0; j < stores.length; j++){ + totalStorePerHour += stores[j][i]; + } + allStoresTotals.push(totalStorePerHour); + } + return allStoresTotals; +}; + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 2 +// +// Pat has decided that he would also like to organize his data as objects containing +// the number of cookies sold per hour and the time. +// Here is sample data for the 9:00 sales: { sales: '88 cookies', time: '9 a.m.' }. +// +// Write a function named salesData that uses forEach to iterate over the hourlySales array +// and create an object for each hour. Return an array of the formatted data. +// ------------------------------------------------------------------------------------------------ + +const salesData = (data) => { + let objectDataArray = []; + let index = 0; + let hourlySales = grandTotal(hoursOpen, cookieStores); + hourlySales.forEach(element => { + let obj1 = {'time': hoursOpen[index], 'sales' : element + ' cookies',}; + objectDataArray.push(obj1); + index += 1; +}); +return objectDataArray; +console.log(hourlySales) +} + + + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 3 +// +// Write a function named giveValentines that takes in an array of names. +// The function should iterate over the array and ensure that each person +// gives a Valentine to every other person in the array, except themself. +// +// Create a message for each valentine exchange following this format: +// "Jerry gives a Valentine to Elaine." +// Use template literals, no string concatenation. Return an array of messages. +// ------------------------------------------------------------------------------------------------ + +const giveValentines = (list) => { + + +}; + +// ------------------------------------------------------------------------------------------------ +// TESTS +// +// All the code below will verify that your functions are working to solve the challenges. +// +// DO NOT CHANGE any of the below code. +// +// Run your tests from the console: jest challenges-02.test.js +// +// ------------------------------------------------------------------------------------------------ + +describe('Testing challenge 1', () => { + test('It should add the hourly totals array', () => { + expect(grandTotal(hoursOpen, cookieStores)).toStrictEqual([ 88, 153, 252, 286, 139, 161, 145, 232, 276, 207, 161, 169 ]); + }); +}); + +describe('Testing challenge 2', () => { + test('It should create an object of data for each store', () => { + expect(salesData(grandTotal(hoursOpen, cookieStores))).toStrictEqual([ + { sales: '88 cookies', time: '9 a.m.', }, + { sales: '153 cookies', time: '10 a.m.', }, + { sales: '252 cookies', time: '11 a.m.', }, + { sales: '286 cookies', time: '12 a.m.', }, + { sales: '139 cookies', time: '1 a.m.', }, + { sales: '161 cookies', time: '2 a.m.', }, + { sales: '145 cookies', time: '3 a.m.', }, + { sales: '232 cookies', time: '4 a.m.', }, + { sales: '276 cookies', time: '5 a.m.', }, + { sales: '207 cookies', time: '6 a.m.', }, + { sales: '161 cookies', time: '7 a.m.', }, + { sales: '169 cookies', time: '8 a.m.', } + ]); + + expect(salesData(grandTotal(hoursOpen, cookieStores)).length).toStrictEqual(hoursOpen.length); + }); +}); + +describe('Testing challenge 3', () => { + test('It should return a list of valentine exchanges', () => { + expect(giveValentines(['Jerry', 'George', 'Elaine', 'Kramer', 'Newman'])).toStrictEqual([ + 'Jerry gives a Valentine to George.', + 'Jerry gives a Valentine to Elaine.', + 'Jerry gives a Valentine to Kramer.', + 'Jerry gives a Valentine to Newman.', + 'George gives a Valentine to Jerry.', + 'George gives a Valentine to Elaine.', + 'George gives a Valentine to Kramer.', + 'George gives a Valentine to Newman.', + 'Elaine gives a Valentine to Jerry.', + 'Elaine gives a Valentine to George.', + 'Elaine gives a Valentine to Kramer.', + 'Elaine gives a Valentine to Newman.', + 'Kramer gives a Valentine to Jerry.', + 'Kramer gives a Valentine to George.', + 'Kramer gives a Valentine to Elaine.', + 'Kramer gives a Valentine to Newman.', + 'Newman gives a Valentine to Jerry.', + 'Newman gives a Valentine to George.', + 'Newman gives a Valentine to Elaine.', + 'Newman gives a Valentine to Kramer.' + ]); + }); +}); \ No newline at end of file diff --git a/objectKeysValueEntries/challenges-06.test.js b/objectKeysValueEntries/challenges-06.test.js new file mode 100644 index 0000000..f38a201 --- /dev/null +++ b/objectKeysValueEntries/challenges-06.test.js @@ -0,0 +1,279 @@ +'use strict'; + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 1 +// +// Write a function named getKeys that takes in an object and returns an array containing the keys +// from the object. +// ------------------------------------------------------------------------------------------------ + +const getKeys = (obj) => { + return Object.keys(obj); +}; + +// // ------------------------------------------------------------------------------------------------ +// // CHALLENGE 2 +// // +// // Write a function named getValues that takes in an object and returns an array containing the +// // values from the object. +// // ------------------------------------------------------------------------------------------------ + +const getValues = (obj) => { + return Object.values(obj); + +} + +// // ------------------------------------------------------------------------------------------------ +// // CHALLENGE 3 +// // +// // Write a function named getEntries that takes in an object and returns an array of the entries +// // (key/value pairs) from the object. +// // ------------------------------------------------------------------------------------------------ + +const getEntries = (obj) => { + return Object.entries(obj); +} + +// // ------------------------------------------------------------------------------------------------ +// // CHALLENGE 4 +// // +// // Write a function named getFrom that takes in an object and a property name and returns the +// // information from the object. For example, if invoked with "courseInfo" and "keys" as arguments, +// // it should return an array containing the keys for the courseInfo object +// // (['name', 'duration', 'topics', 'finalExam']). +// // +// // This will make our code more dynamic and DRY. +// // ------------------------------------------------------------------------------------------------ +// const courseInfo = { name: 'Code 301', duration: { dayTrack: '4 weeks', eveningTrack: '8 weeks'}, +// topics: ['SMACSS', 'APIs', 'NodeJS', 'SQL', 'jQuery', 'functional programming'], +// finalExam: true }; + +const getFrom = (obj, property) => { + if(property === 'keys') { + return getKeys(obj); + } else if (property === 'value') { + return getValues(obj); + } else if (property === 'entries') { + return getEntries(obj); + } +}; + +// // ------------------------------------------------------------------------------------------------ +// // CHALLENGE 5 +// // +// // Use the characters data below for the rest of the challenges. +// // +// // Write a function named totalCharacters that takes in an array and returns the number of +// // characters in the array. Use the getFrom function you wrote in challenge 4. +// // ------------------------------------------------------------------------------------------------ + +let characters = [ + { + name: 'Eddard', + spouse: 'Catelyn', + children: ['Robb', 'Sansa', 'Arya', 'Bran', 'Rickon'], + house: 'Stark' + }, + { + name: 'Jon', + spouse: 'Lysa', + children: ['Robin'], + house: 'Arryn' + }, + { + name: 'Cersei', + spouse: 'Robert', + children: ['Joffrey', 'Myrcella', 'Tommen'], + house: 'Lannister' + }, + { + name: 'Daenarys', + spouse: 'Khal Drogo', + children: ['Drogon', 'Rhaegal', 'Viserion'], + house: 'Targaryen' + }, + { + name: 'Mace', + spouse: 'Alerie', + children: ['Margaery', 'Loras'], + house: 'Tyrell' + }, + { + name: 'Sansa', + spouse: 'Tyrion', + children: [], + house: 'Stark' + }, + { + name: 'Jon', + spouse: null, + children: [], + house: 'Snow' + } +] + +const totalCharacters = (arr) => { + //the number of character objects within in the character array/object. + //forEach that goes over the full array. For each character object within the array, a new variable called NumberOfCharacters ++ + getFrom(arr, name).map(); + // this should pull in characters array, and then get the key value of name and enter it into an array, then after this new array is created the .length() get the length of the array in a number format. + +}; + +// // ------------------------------------------------------------------------------------------------ +// // CHALLENGE 6 +// // +// // Write a function named getHouses that returns an array of the houses in the data set. +// // Use the getFrom function you wrote in challenge 4. +// // ------------------------------------------------------------------------------------------------ +// const getHouses = (arr) => { +// // Solution code here... +// } + +// // ------------------------------------------------------------------------------------------------ +// // CHALLENGE 7 +// // +// // Write a function named hasChildrenValues that takes in the data and a name and returns a boolean +// // based on whether that character has children. Use the getFrom function you wrote in challenge 4. +// // ------------------------------------------------------------------------------------------------ + +// const hasChildrenValues = (arr, character) => { +// // Solution code here... +// } + +// // ------------------------------------------------------------------------------------------------ +// // CHALLENGE 8 +// // +// // Write a function named hasChildrenEntries that is similar to your hasChildrenValues function +// // from challenge 7, but uses the data's entries instead of its keys. +// // Use the getFrom function you wrote in challenge 4. +// // ------------------------------------------------------------------------------------------------ + +// const hasChildrenEntries = (arr, character) => { +// // Solution code here... +// } + +// // ------------------------------------------------------------------------------------------------ +// // CHALLENGE 9 +// // +// // Write a function named houseSize that takes in the array and returns an object for each house +// // containing the name of the house and the number of members. +// // For example: { house: 'Stark', members: 7 }. Use the getFrom function you wrote in challenge 4. +// // ------------------------------------------------------------------------------------------------ + +// const houseSize = (arr) => { +// // Solution code here... +// } + +// // ------------------------------------------------------------------------------------------------ +// // CHALLENGE 10 +// // +// // As fans are well aware, "When you play the game of thrones, you win or you die. There is no middle ground." +// // +// // We will assume that Alerie Tyrell is deceased. She missed her daughter's wedding. Twice. +// // +// // Write a function named houseSurvivors. Modify your houseSize function from challenge 9 to use +// // as the basis of this function. +// // If the spouse is deceased, do not include him/her in the total number of family members. +// // ------------------------------------------------------------------------------------------------ + +// const deceasedSpouses = ['Catelyn', 'Lysa', 'Robert', 'Khal Drogo', 'Alerie']; + +// const houseSurvivors = (arr) => { +// // Solution code here... +// } + +// ------------------------------------------------------------------------------------------------ +// TESTS +// +// All the code below will verify that your functions are working to solve the challenges. +// +// DO NOT CHANGE any of the below code. +// +// Run your tests from the console: jest challenges-06.test.js +// +// ------------------------------------------------------------------------------------------------ + +describe('Tests using the course info object', () => { + const courseInfo = { name: 'Code 301', duration: { dayTrack: '4 weeks', eveningTrack: '8 weeks'}, + topics: ['SMACSS', 'APIs', 'NodeJS', 'SQL', 'jQuery', 'functional programming'], + finalExam: true }; + + describe('Testing challenge 1', () => { + test('It should return the keys from an object', () => { + expect(getKeys(courseInfo)).toStrictEqual([ 'name', 'duration', 'topics', 'finalExam' ]); + }); + }); + + describe('Testing challenge 2', () => { + test('It should return the values from an object', () => { + expect(getValues(courseInfo)).toStrictEqual([ 'Code 301', { dayTrack: '4 weeks', eveningTrack: '8 weeks' }, [ 'SMACSS', 'APIs', 'NodeJS', 'SQL', 'jQuery', 'functional programming' ], true ]); + }); + }); + + describe('Testing challenge 3', () => { + test('It should return the entries from an object', () => { + expect(getEntries(courseInfo)).toStrictEqual([ [ 'name', 'Code 301' ], [ 'duration', { dayTrack: '4 weeks', eveningTrack: '8 weeks' } ], [ 'topics', [ 'SMACSS', 'APIs', 'NodeJS', 'SQL', 'jQuery', 'functional programming' ] ], [ 'finalExam', true ] ]); + }); + }); + + describe('Testing challenge 4', () => { + test('It should return the keys from an object', () => { + expect(getFrom(courseInfo, 'keys')).toStrictEqual([ 'name', 'duration', 'topics', 'finalExam' ]); + }); + + test('It should return the values from an object', () => { + expect(getFrom(courseInfo, 'values')).toStrictEqual([ 'Code 301', { dayTrack: '4 weeks', eveningTrack: '8 weeks' }, [ 'SMACSS', 'APIs', 'NodeJS', 'SQL', 'jQuery', 'functional programming' ], true ]); + }); + + test('It should return the entries from an object', () => { + expect(getFrom(courseInfo, 'entries')).toStrictEqual([ [ 'name', 'Code 301' ], [ 'duration', { dayTrack: '4 weeks', eveningTrack: '8 weeks' } ], ['topics', [ 'SMACSS', 'APIs', 'NodeJS', 'SQL', 'jQuery', 'functional programming' ] ], [ 'finalExam', true ] ]); + }); + }); +}) + +describe('Testing challenge 5', () => { + test('something specific', () => { + expect(totalCharacters(characters)).toStrictEqual(7); + }); +}); + +describe('Testing challenge 6', () => { + test('something specific', () => { + expect(getHouses(characters)).toStrictEqual([ 'Stark', 'Arryn', 'Lannister', 'Targaryen', 'Tyrell', 'Stark', 'Snow' ]); + expect(getHouses(characters).length).toStrictEqual(7); + }); +}); + +describe('Testing challenge 7', () => { + test('It should return true for characters that have children', () => { + expect(hasChildrenValues(characters, 'Daenarys')).toBeTruthy(); + }); + + test('It should return false to characters who do not have children', () => { + expect(hasChildrenValues(characters, 'Sansa')).toBeFalsy(); + }); +}); + +describe('Testing challenge 8', () => { + test('It should return true for characters that have children', () => { + expect(hasChildrenEntries(characters, 'Eddard')).toBeTruthy(); + }); + + test('It should return false to characters who do not have children', () => { + expect(hasChildrenEntries(characters, 'Jon S.')).toBeFalsy(); + }); +}); + +describe('Testing challenge 9', () => { + test('It should return an object for each house containing the name and size', () => { + expect(houseSize(characters)).toStrictEqual([ { house: 'Stark', members: 7 }, { house: 'Arryn', members: 3 }, { house: 'Lannister', members: 5 }, { house: 'Targaryen', members: 5 }, { house: 'Tyrell', members: 4 }, { house: 'Stark', members: 2 }, { house: 'Snow', members: 1 } ]); + expect(houseSize(characters).length).toStrictEqual(7); + }); +}); + +describe('Testing challenge 10', () => { + test('It should not include any deceased spouses', () => { + expect(houseSurvivors(characters)).toStrictEqual([ { house: 'Stark', members: 6 }, { house: 'Arryn', members: 2 }, { house: 'Lannister', members: 4 }, { house: 'Targaryen', members: 4 }, { house: 'Tyrell', members: 3 }, { house: 'Stark', members: 2 }, { house: 'Snow', members: 1 } ]); + }); +}); \ No newline at end of file diff --git a/reduce/challenges-09.test.js b/reduce/challenges-09.test.js new file mode 100644 index 0000000..fac0081 --- /dev/null +++ b/reduce/challenges-09.test.js @@ -0,0 +1,323 @@ +'use strict'; + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 1 +// +// Write a function named countNumberOfElements that, given an array as input, +// uses reduce to count the number of elements in the array. +// +// Note: You may not use the array's built-in length property. +// ------------------------------------------------------------------------------------------------ +// [0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array) { return accumulator + currentValue; }); + +const countNumberOfElements = (input) => { + let initialValue = 0; + return input.reduce(function (accumulator, currentValue) { + // console.log('CURRENT VALUE!!!!',currentValue); + // console.log(accumulator) + accumulator += 1; + return accumulator; + }, initialValue) +}; +//------------------------------------------------------------------------------------------------ +// CHALLENGE 2 +// +// Write a function named countNumberOfChildren that, given the array of characters, below, +// uses reduce to return the total number of children in the data set. +// +// ------------------------------------------------------------------------------------------------ + +const characters = [ + { + name: 'Eddard', + spouse: 'Catelyn', + children: ['Robb', 'Sansa', 'Arya', 'Bran', 'Rickon'], + house: 'Stark', + }, + { + name: 'Jon', + spouse: 'Lysa', + children: ['Robin'], + house: 'Arryn', + }, + { + name: 'Cersei', + spouse: 'Robert', + children: ['Joffrey', 'Myrcella', 'Tommen'], + house: 'Lannister', + }, + { + name: 'Daenarys', + spouse: 'Khal Drogo', + children: ['Drogon', 'Rhaegal', 'Viserion'], + house: 'Targaryen', + }, + { + name: 'Mace', + spouse: 'Alerie', + children: ['Margaery', 'Loras'], + house: 'Tyrell', + }, + { + name: 'Sansa', + spouse: 'Tyrion', + house: 'Stark', + }, + { + name: 'Jon', + spouse: null, + house: 'Snow', + }, +]; + +const countNumberOfChildren = (input) => { + let numberOfChildern = []; + let totalChildern = []; + return input.reduce( (accumulator, currentValue) => + { + console.log(currentValue.children); + // console.log(accumulator) + // console.log(currentValue.childern.length); + // console.log(numberChildern) + //NEED: a function that checks if any childern exist if they do push them to the numberOfChildern {} + numberOfChildern[currentValue.childern] = currentValue.childern; + + accumulator += 1; + return accumulator; + }); +}; + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 3 +// +// Write a function named extractState that, given the snorlaxData, below, +// uses reduce to return the object whose 'name' property matches the given string. +// +// If the input array does not have a stat with that specific name, the function should return null. +// ------------------------------------------------------------------------------------------------ + +const snorlaxData = { + stats: [ + { + stat: { + url: 'https://pokeapi.co/api/v2/stat/6/', + name: 'speed', + }, + effort: 5, + baseStat: 30, + }, + { + stat: { + url: 'https://pokeapi.co/api/v2/stat/5/', + name: 'special-defense', + }, + effort: 2, + baseStat: 110, + }, + { + stat: { + url: 'https://pokeapi.co/api/v2/stat/4/', + name: 'special-attack', + }, + effort: 9, + baseStat: 65, + }, + ], + name: 'snorlax', + weight: 4600, +}; + +const extractStat = (statName, input) => { + + let UrlofStat = ''; + return input.reduce(function (accumulator,currentValue, statName) + { + console.log(statName); + //NEED: need a function that checks the input of url and if it is empty returyns null + return accumulator; + }); +} + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 4 +// Write a function that, given an array of numbers as input, uses ONE call to filter to +// calculate the array's average value. +// ------------------------------------------------------------------------------------------------ + +// const calculateAverage = (input) => { +// input.reduce((accumulator, currentValue) => { + +// accumulator = ; +// }); +// }; + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 5 +// +// Write a function named extractChildren that, given the array of characters from challenge 2, +// accomplishes the following: +// 1) Uses filter to return an array of the characters that contain the letter 'a' in their name +// 2) Then, uses reduce to return an array of all the children's names in the filtered array +// +// ------------------------------------------------------------------------------------------------ + +const extractChildren = input => { + // Solution code here... +}; + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 6 +// +// Write a function named reversedString that takes in a string and returns +// a string with the letters in reverse order. +// +// Note: You must use reduce for this challenge. You may not use the built-in .reverse() string method. +// ------------------------------------------------------------------------------------------------ + +const reversedString = (input) => { + // Solution code here... +}; + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 7 +// +// Write a function named countPrimeNumbers that, given an array elements as input, +// uses reduce to count the number of elements that are prime numbers. +// +// You are welcome to use the provided isPrime function. +// ------------------------------------------------------------------------------------------------ + +const isPrime = (value) => { + for (let i = 2; i < value; i++) { + if (value % i === 0) { + return false; + } + } + return value > 1; +}; + +const countPrimeNumbers = (input) => { + // Solution code here... +} + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 8 +// +// Write a function named returnNames that, given the Star Wars data, below, +// uses reduce to return an array containing the names of the characters. +// ------------------------------------------------------------------------------------------------ + +let starWarsData = [{ + name: 'Luke Skywalker', + height: '172', + mass: '77', + hair_color: 'blond', + skin_color: 'fair', + eye_color: 'blue', + birth_year: '19BBY', + gender: 'male', +}, +{ + name: 'C-3PO', + height: '167', + mass: '75', + hair_color: 'n/a', + skin_color: 'gold', + eye_color: 'yellow', + birth_year: '112BBY', + gender: 'n/a'}, +{ + name: 'R2-D2', + height: '96', + mass: '32', + hair_color: 'n/a', + skin_color: 'white, blue', + eye_color: 'red', + birth_year: '33BBY', + gender: 'n/a' +}, +{ + name: 'Darth Vader', + height: '202', + mass: '136', + hair_color: 'none', + skin_color: 'white', + eye_color: 'yellow', + birth_year: '41.9BBY', + gender: 'male' +}, +{ + name: 'Leia Organa', + height: '150', + mass: '49', + hair_color: 'brown', + skin_color: 'light', + eye_color: 'brown', + birth_year: '19BBY', + gender: 'female' +}] + +const returnNames = (data) => { + // Solution code here... +}; + +// ------------------------------------------------------------------------------------------------ +// TESTS +// +// All the code below will verify that your functions are working to solve the challenges. +// +// DO NOT CHANGE any of the below code. +// +// Run your tests from the console: jest challenges-09.test.js +// +// ------------------------------------------------------------------------------------------------ + +describe('Testing challenge 1', () => { + test('It should return the length of the array', () => { + expect(countNumberOfElements([1, 2, 3, 4, 5])).toStrictEqual(5); + }); +}); + +describe('Testing challenge 2', () => { + test('It should return the total number of children', () => { + expect(countNumberOfChildren(characters)).toStrictEqual(14); + }); +}); + +describe('Testing challenge 3', () => { + test('It should return any stats that match the input', () => { + expect(extractStat('speed', snorlaxData.stats)).toStrictEqual({ stat: { url: 'https://pokeapi.co/api/v2/stat/6/', name: 'speed' }, effort: 5, baseStat: 30 }); + }); +}); + +describe('Testing challenge 4', () => { + test('It should return the average of the numbers in the array', () => { + expect(calculateAverage([18, 290, 37, 4, 55, 16, 7, 85 ])).toStrictEqual(64); + }); +}); + +describe('Testing challenge 5', () => { + test('It should return an array containing the names of the children', () => { + expect(extractChildren(characters)).toStrictEqual([ 'Robb', 'Sansa', 'Arya', 'Bran', 'Rickon', 'Drogon', 'Rhaegal', 'Viserion', 'Margaery', 'Loras' ]); + expect(extractChildren(characters).length).toStrictEqual(10); + }); +}); + +describe('Testing challenge 6', () => { + test('It should return the string with the characters in reverse order', () => { + expect(reversedString('Code 301')).toStrictEqual('103 edoC'); + }); +}); + +describe('Testing challenge 7', () => { + test('It should return a count of the prime numbers in the array', () => { + expect(countPrimeNumbers([1, 2, 13, 64, 45, 56, 17, 8])).toStrictEqual(3); + }); +}); + +describe('Testing challenge 8', () => { + test('It should return a count of the prime numbers in the array', () => { + expect(returnNames(starWarsData)).toStrictEqual([ 'Luke Skywalker', 'C-3PO', 'R2-D2', 'Darth Vader', 'Leia Organa' ]); + expect(returnNames(starWarsData).length).toStrictEqual(5); + }); +}); \ No newline at end of file diff --git a/regularExpressionsPt1/challenges-04.test.js b/regularExpressionsPt1/challenges-04.test.js new file mode 100644 index 0000000..1332488 --- /dev/null +++ b/regularExpressionsPt1/challenges-04.test.js @@ -0,0 +1,206 @@ +'use strict'; + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 1 +// +// Write a function named isNum that takes in a string or number of any length. +// This function should use a regular expression pattern to return true if the input +// contains a number, and false if the input does not contain a number. +// +// Example input/output: +// 12345 => true +// '12345' => true +// 'h3llo world' => true +// 'hello world' => false +// ------------------------------------------------------------------------------------------------ + +const isNum = (num) => { + // Solution code here... +}; + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 2 +// +// Write a function named isCapitalized that takes in a string. This function should use a +// regular expression pattern to match all words that begin with a capital letter. +// +// Return an array containing all the matches. +// ------------------------------------------------------------------------------------------------ + +const isCapitalized = (string) => { + // Solution code here... +}; + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 3 +// +// Write a function named citiesAtoJ that takes in an array of city names and uses a regular expression +// pattern to return a new array containing any cities that begin with the letters A through J, inclusive. +// ------------------------------------------------------------------------------------------------ + +const citiesAtoJ = (cities) => { + // Solution code here... +}; + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 4 +// +// You have created a game application and begin by asking users an easy question: In which month is Halloween? +// +// Write a function named matchMonth which uses a regular expression pattern to match any of these inputs: +// October, Oct, october, oct +// +// If the user enters any of these four inputs, return true. For ANY other input, return false. +// Do not use the vertical bar (pipe) in your pattern. +// ------------------------------------------------------------------------------------------------ + +const matchMonth = (input) => { + // Solution code here... +}; + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 5 +// +// Write a function named noPunctuation that contains a regular expression pattern to find +// all of the words that contain a space immediately at the end of the word. Return an array of all +// such words, still containing the space at the end. +// +// For example, if given the string "Hello, and have a wonderful day!", +// the word "Hello, " would not be returned because it is immediately followed by a comma, +// and the word "day!" would not be returned because it is immediately followed by an exclamation point. +// The expected output is ["and ", "have ", "a ", "wonderful "]. +// ------------------------------------------------------------------------------------------------ + +const noPunctuation = input => { + // Solution code here... +}; + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 6 +// +// You want to teach a friend how to play hangman and want to show them using a partially complete puzzle. +// +// Write a function named hangman which uses the replace method to remove all of the +// vowels (a, e, i, o, u) from the hangman string and replace them with an underscore. +// This will result in a printout where the string contains all consonants, and +// underscores where the vowels were previously located. +// +// For example, 'Welcome to Code 301!' will return 'W_lc_m_ t_ C_d_ 301!'. +// ------------------------------------------------------------------------------------------------ + +let hangman = (str) => { + // Solution code here... +}; + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 7 +// +// Write a function named findShells that takes in the string below and uses a regular +// expression pattern to find all instances of the following words: "sells", "shells", "seashells". +// Do not use the vertical bar (pipe) character. +// +// Hint: All of these words end with the letters "ells". +// ------------------------------------------------------------------------------------------------ + +const seashells = 'She sells seashells by the seashore. The shells she sells are surely seashells. So if she sells shells on the seashore, I\'m sure she sells seashore shells.'; + +const findShells = (phrase) => { + // Solution code here... +}; + +// ------------------------------------------------------------------------------------------------ +// TESTS +// +// All the code below will verify that your functions are working to solve the challenges. +// +// DO NOT CHANGE any of the below code. +// +// Run your tests from the console: jest challenges-04.solution.test.js +// +// ------------------------------------------------------------------------------------------------ + +describe('Testing challenge 1', () => { + test('It should return true if the input is a number', () => { + expect(isNum(1234567890)).toBeTruthy(); + expect(isNum('12345')).toBeTruthy(); + }); + test('It should return true if the input contains a number', () => { + expect(isNum('h3llo w0rld')).toBeTruthy(); + }); + test('It should return false if the input does not contain a number', () => { + expect(isNum('hello world')).toBeFalsy(); + expect(isNum('')).toBeFalsy(); + }); +}); + +describe('Testing challenge 2', () => { + test('It should only return words that begin with a capital letter', () => { + const capitalResult = isCapitalized('We only want to Return the Words that begin With a capital Letter'); + + expect(capitalResult).toStrictEqual([ 'We', 'Return', 'Words', 'With', 'Letter' ]); + expect(capitalResult.length).toStrictEqual(5); + }); +}); + +describe('Testing challenge 3', () => { + let cities = ['Cleveland', 'San Diego', 'Birmingham', 'Seattle', 'Miami', 'New York City', 'Omaha', 'Portland', 'Austin', 'Boston', 'Newport Beach', 'Hoboken']; + + test('It should return the cities whose names begin with the letters A through J', () => { + expect(citiesAtoJ(cities)).toContain('Cleveland', 'Birmingham', 'Austin', 'Boston', 'Hoboken'); + expect(citiesAtoJ(cities).length).toStrictEqual(5); + }); + + test('It should not return the cities whose names begin with the letters K through Z', () => { + expect(citiesAtoJ(cities)).not.toContain('San Diego', 'Seattle', 'Miami', 'New York City', 'Omaha', 'Portland', 'Newport Beach'); + }); +}); + +describe('Testing challenge 4', () => { + test('It should match any of the acceptable inputs', () => { + expect(matchMonth('Oct')).toBeTruthy(); + expect(matchMonth('oct')).toBeTruthy(); + expect(matchMonth('October')).toBeTruthy(); + expect(matchMonth('october')).toBeTruthy(); + }); + + test('It should not match anything other than the acceptable inputs', () => { + expect(matchMonth('November')).toBeFalsy(); + expect(matchMonth('nov')).toBeFalsy(); + expect(matchMonth(123)).toBeFalsy(); + expect(matchMonth('octob')).toBeFalsy(); + expect(matchMonth('OCTOBER')).toBeFalsy(); + expect(matchMonth('notOctober')).toBeFalsy(); + }); +}); + +describe('Testing challenge 5', () => { + const lorem = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras lacinia vel massa sed egestas. Nunc faucibus iaculis elit, a scelerisque enim condimentum sed. Aenean ac scelerisque sem, et pharetra diam.'; + + test('It should only return words that are immediately followed by a space', () => { + expect(noPunctuation(lorem)).toStrictEqual([ 'Lorem ', 'ipsum ', 'dolor ', 'sit ', 'consectetur ', 'adipiscing ', 'Cras ', 'lacinia ', 'vel ', 'massa ', 'sed ', 'Nunc ', 'faucibus ', 'iaculis ', 'a ', 'scelerisque ', 'enim ', 'condimentum ', 'Aenean ', 'ac ', 'scelerisque ', 'et ', 'pharetra ' ]); + expect(noPunctuation(lorem).length).toStrictEqual(23); + }); + + test('It should not contain words that are followed by any non-space character', () => { + expect(noPunctuation(lorem)).not.toContain(['amet,', 'elit.', 'egestas.', 'elit,', 'sed.', 'sem,', 'diam.', 'nibh.', 'porttitor.', 'euismod,', 'ultrices.', 'massa,', 'vel,', 'purus.', 'purus,', 'odio.', 'aliquet,', 'non,', 'sem.']) + }); +}); + +describe('Testing challenge 6', () => { + let startString = 'This is a regex challenge. We are trying to create a hangman phrase where all of the vowels are missing!'; + + test('It should remove the vowels from the hangman string and replace them with underscores', () => { + expect(hangman(startString)).toStrictEqual('Th_s _s _ r_g_x ch_ll_ng_. W_ _r_ try_ng t_ cr__t_ _ h_ngm_n phr_s_ wh_r_ _ll _f th_ v_w_ls _r_ m_ss_ng!'); + }); + + test('It should not contain the letters "a", "e", "i", "o", or "u"', () => { + expect(hangman(startString)).not.toContain('a', 'e', 'i', 'o', 'u'); + }); +}); + +describe('Testing challenge 7', () => { + test('It should return an array of instances of "sells", shells", and "seashells"', () => { + expect(findShells(seashells)).toStrictEqual(['sells', 'seashells', 'shells', 'sells', 'seashells', 'sells', 'shells', 'sells', 'shells']); + expect(findShells(seashells).length).toStrictEqual(9); + }); +}); \ No newline at end of file diff --git a/splitJoinSliceSplice/challenges-05.test.js b/splitJoinSliceSplice/challenges-05.test.js new file mode 100644 index 0000000..680a659 --- /dev/null +++ b/splitJoinSliceSplice/challenges-05.test.js @@ -0,0 +1,291 @@ +'use strict'; + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 1 +// +// Write a function named howMuchPencil that takes in a string, as written on the side of a pencil. +// As you sharpen the pencil, the string will become shorter and shorter, starting by removing the +// first letter. +// +// Your function should use slice within a loop and return an array of each successive string +// result from losing letters to the sharpener, until nothing is left. +// +// For example, if the input is 'Welcome', the output will be: +// ['Welcome', 'elcome', 'lcome', 'come', 'ome', 'me', 'e', '']. +// ------------------------------------------------------------------------------------------------ + +const howMuchPencil = (name) => { + let result = []; + // Solution code here... + return result; +}; + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 2 +// +// Write a function name wordsToCharList that, given a string as input, returns a new array where every element is a +// character of the input string. +// +// For example, wordsToCharList('gregor') returns ['g','r','e','g','o','r']. +// ------------------------------------------------------------------------------------------------ + +const wordsToCharList = (input) => { + // Solution code here... +}; + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 3 +// +// Write a function named totalSumCSV that, given a string of comma-separated values (CSV) as input +// (e.g. "1,2,3"), returns the total sum of the numeric values (e.g. 6). +// ------------------------------------------------------------------------------------------------ + +const totalSumCSV = (input) => { + let total = 0; + // Solution code here... + return total; +}; + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 4 +// +// You are making a grocery list for ingredients needed in the gruffalo crumble recipe, below. +// Rather than taking the entire recipe, you only want a list of the item names. +// +// Write a function named listFoods that takes in the recipe and returns a new array of the food items +// without any amount or units. Just the name. For example, '1 cup flour' will return 'flour'. +// +// Use slice for this function, maybe more than once. The Array.indexOf() method may also be helpful. +// Do NOT use split for this function. +// ------------------------------------------------------------------------------------------------ + +const gruffaloCrumble = { + name: 'How to make a Gruffalo Crumble', + ingredients: [ + '1 medium-sized Gruffalo', + '8 pounds oats', + '2 pounds brown sugar', + '4 pounds flour', + '2 gallons pure maple syrup', + '16 cups chopped nuts', + '1 pound baking soda', + '1 pound baking powder', + '1 pound cinnamon', + '6 gallons melted butter', + '2 gallons fresh water', + ], + steps: [ + 'Pre-heat a large oven to 375', + 'De-prickle the gruffalo', + 'Sprinkle with cinnamon, sugar, flour, and nuts', + 'Mix until evenly distributed', + 'Grease a 3-foot x 3-foot casserole dish', + 'Combine gruffalo compote with water to maintain moisture in the oven', + 'Fold together remaining ingredients to make the crisp', + 'Spread the crisp evenly over the gruffalo mixture', + 'Bake for 12-15 hours', + ] +} + + +const listFoods = (recipe) => { + let result = []; + // Solution code here... + return result; +} + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 5 +// +// Use the same recipe from challenge 4, above. +// +// Write a function named stepAction that takes in the recipe and extracts the action verbs from the steps. +// Return a new array containing just the verbs. For example, ['Mix until evenly distributed'] returns ['Mix']. +// +// Use the split method for this function. +// ------------------------------------------------------------------------------------------------ + +const stepActions = (recipe) => { + let result = []; + // Solution code here... + return result; +} + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 6 +// +// Write a function named splitFoods that uses split to produce the same output as challenge 4. +// You may also use other array/string functions. +// ------------------------------------------------------------------------------------------------ + +const splitFoods = (recipe) => { + let result = []; + // Solution code here... + return result; +} + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 7 +// +// Write a function named removeEvenValues that, given an array of integers as input, +// deletes all even values from the array, leaving no 'gaps' behind. +// The array should be modified in-place. +// +// For example: +// let list = [1, 2, 3, 4, 5, 6]; +// removeEvenValues(list); +// console.log(list); //--> [1, 3, 5] +// ------------------------------------------------------------------------------------------------ + +const removeEvenValues = (input) => { + // Solution code here... +}; + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 8 +// +// Write a function named removeLastCharacters that takes in a string and a number. +// This function should remove a certain number of characters from the end of the string. +// The number argument determines how many characters to remove. Return the resulting string. +// +// If the number argument is greater than the length of the input string the function should +// return an empty string. If the number argument input is a negative number, +// the function should return the input string without any changes. +// +// For example: removeLastCharacters('Gregor', 2) returns 'Greg'. +// ------------------------------------------------------------------------------------------------ + +const removeLastCharacters = (str, numberOfCharacters) => { + // Solution code here... +}; + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 9 +// +// Write a function named removeVowels that takes in a string and returns a new string +// where all the vowels of the original string have been removed. +// +// For example, removeVowels('gregor') returns 'grgr'. +// ------------------------------------------------------------------------------------------------ + +const removeVowels = (input) => { + // Solution code here... +}; + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 10 +// +// Write a function named extractVowels that takes in a string and returns an array +// where the first element is the original string with all the vowels removed, +// and the second element is a string of all the vowels that were removed, in alphabetical order. +// +// For example, extractVowels('gregor') returns ['grgr', 'eo']. +// Similarly, extractVowels('The quick brown fox') returns ['Th qck brwn fx', 'eioou'] +// ------------------------------------------------------------------------------------------------ + +const extractVowels = (input) => { + // Solution code here... +}; + +// ------------------------------------------------------------------------------------------------ +// TESTS +// +// All the code below will verify that your functions are working to solve the challenges. +// +// DO NOT CHANGE any of the below code. +// +// Run your tests from the console: jest challenges-05.test.js +// +// ------------------------------------------------------------------------------------------------ + +describe('Testing challenge 1', () => { + test('It should return a list of shortening words', () => { + expect(howMuchPencil('Welcome')).toStrictEqual(['Welcome', 'elcome', 'lcome', 'come', 'ome', 'me', 'e', '']); + expect(howMuchPencil('Welcome').length).toStrictEqual(8); + expect(howMuchPencil('')).toStrictEqual(['']); + expect(howMuchPencil('abc')).toStrictEqual(['abc', 'bc', 'c', '']); + }); +}); + +describe('Testing challenge 2', () => { + test('It should return an array of individual letters', () => { + expect(wordsToCharList('Gregor')).toStrictEqual(['G','r','e','g','o','r']); + expect(wordsToCharList('Gregor').length).toStrictEqual(6); + expect(wordsToCharList('hooray')).toStrictEqual(['h','o','o','r','a','y']); + expect(wordsToCharList('')).toStrictEqual([]); + }); +}); + +describe('Testing challenge 3', () => { + test('It should add up the numbers contained within the string', () => { + expect(totalSumCSV('1,4,5,7,2')).toStrictEqual(19); + expect(totalSumCSV('147')).toStrictEqual(147); + }); +}); + +describe('Testing challenge 4', () => { + test('It should return a list of foods', () => { + expect(listFoods(gruffaloCrumble)).toStrictEqual(['Gruffalo', 'oats', 'brown sugar', 'flour', 'pure maple syrup', 'chopped nuts', 'baking soda', 'baking powder', 'cinnamon', 'melted butter', 'fresh water']); + expect(listFoods(gruffaloCrumble).length).toStrictEqual(11); + }); +}); + +describe('Testing challenge 5', () => { + test('It should return a list of recipe steps', () => { + expect(stepActions(gruffaloCrumble)).toStrictEqual(['Pre-heat', 'De-prickle', 'Sprinkle', 'Mix', 'Grease', 'Combine', 'Fold', 'Spread', 'Bake']); + expect(stepActions(gruffaloCrumble).length).toStrictEqual(9); + }); +}); + +describe('Testing challenge 6', () => { + test('It should return a list of foods', () => { + expect(splitFoods(gruffaloCrumble)).toStrictEqual(['Gruffalo', 'oats', 'brown sugar', 'flour', 'pure maple syrup', 'chopped nuts', 'baking soda', 'baking powder', 'cinnamon', 'melted butter', 'fresh water']); + }); +}); + +describe('Testing challenge 7', () => { + test('It should remove the even numbers from the array', () => { + let list = [1, 2, 3, 4, 5, 6]; + removeEvenValues(list); + expect(list).toStrictEqual([1, 3, 5]); + + list = [6, 3, 19, 43, 12, 66, 43]; + removeEvenValues(list); + expect(list).toStrictEqual([3, 19, 43, 43]); + expect(list.length).toStrictEqual(4); + }); +}); + +describe('Testing challenge 8', () => { + test('It should shorten the string based on the first argument', () => { + expect(removeLastCharacters('Gregor', 2)).toStrictEqual('Greg'); + expect(removeLastCharacters('Gregor', 2).length).toStrictEqual(4); + }); + test('It should return the complete string when passed a negative number', () => { + expect(removeLastCharacters('hello', -1)).toStrictEqual('hello'); + expect(removeLastCharacters('wowow', -700)).toStrictEqual('wowow'); + }); + test('It should return an empty string when called with a number larger than the string length', () => { + expect(removeLastCharacters('hello', 12)).toStrictEqual(''); + expect(removeLastCharacters('', 1)).toStrictEqual(''); + expect(removeLastCharacters('a', 1)).toStrictEqual(''); + }); +}); + +describe('Testing challenge 9', () => { + test('It should return the string without vowels', () => { + expect(removeVowels('gregor')).toStrictEqual('grgr'); + expect(removeVowels('gregor').length).toStrictEqual(4); + expect(removeVowels('asdf')).toStrictEqual('sdf'); + expect(removeVowels('why')).toStrictEqual('why'); + }); +}); + +describe('Testing challenge 10', () => { + test('It should return the string without vowels', () => { + expect(extractVowels('gregor')).toStrictEqual(['grgr', 'eo']); + expect(extractVowels('gregor').length).toStrictEqual(2); + + expect(extractVowels('The quick brown fox')).toStrictEqual(['Th qck brwn fx', 'eioou']); + }); +}); \ No newline at end of file diff --git a/two-dimensionalArray/challenges-03.test.js b/two-dimensionalArray/challenges-03.test.js new file mode 100644 index 0000000..affb157 --- /dev/null +++ b/two-dimensionalArray/challenges-03.test.js @@ -0,0 +1,315 @@ +'use strict'; + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 1 +// +// Write a function named findFourteen that returns the number 14 from the nested array. +// Hint: refresh on how to access elements at a specific index in an array. +// ------------------------------------------------------------------------------------------------ + +const nestedArray = [ [ [1, 2, 3], [4, 5, 6] ], [ [7, 8, 9], [10, 11, 12] ], [ [13, 14, 15], [16, 17, 18] ] ]; + +const findFourteen = (array) => { + // Solution code here... +} + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 2 +// +// Write a function named howManyTreats that will return the quantity of treats +// you need to pick up from the pet store today from this array. +// ------------------------------------------------------------------------------------------------ + +const errands = [ + { store: 'Grocery store', + items: [ { name: 'Eggs', quantity: 12 }, { name: 'Milk', quantity: 1 }, { name: 'Apples', quantity: 3 }] + }, + { store: 'Drug store', + items: [ { name: 'Toothpaste', quantity: 1 }, { name: 'Toothbrush', quantity: 3 }, { name: 'Mouthwash',quantity: 1 } ] + }, + { store: 'Pet store', + items: [ { name: 'Cans of food', quantity: 8 }, { name: 'Treats', quantity: 24 }, { name: 'Leash', quantity: 1 } ] + } +] + +const howManyTreats = (arr) => { + // Solution code here... +} + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 3 +// +// Write a function named battleship that accepts a 2D array and two numbers, a row coordinate and a column coordinate. +// Return "hit" or "miss" depending on if there's part of a boat at that position in the array. +// Assume the array has only one of two values at each index. '# for part of a boat, or ' ' for open water. +// +// Here is a sample board: +// [ +// ['#', ' ', '#', ' '], +// ['#', ' ', '#', ' '], +// ['#', ' ', ' ', ' '], +// [' ', ' ', '#', '#'], +// ] +// +// The top row of the board is considered row zero and row numbers increase as they go down. +// ------------------------------------------------------------------------------------------------ + +const battleship = (board, row, col) => { + // Solution code here... +} + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 4 +// +// Write a function named calculateProduct that takes in a two-dimensional array of numbers, +// multiplies all of the numbers in each array, and returns the final product. +// This function should work for any number of inner arrays. +// +// For example, the following input returns a product of 720: [[1,2], [3,4], [5,6]] +// ------------------------------------------------------------------------------------------------ + +const calculateProduct = (numbers) => { + // Solution code here... +} + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 5 +// +// Write a function named averageDailyTemperature that accepts a two-dimensional array representing +// average daily temperatures grouped week-by-week. +// Calculate the average daily temperature during that entire period. (Your output should be a single number.) +// Write your function so it could accept an array with any number of weeks given to it. +// ------------------------------------------------------------------------------------------------ + +// Real daily average temperatures for Seattle, October 1-28 2017 +const weeklyTemperatures = [ + [66, 64, 58, 65, 71, 57, 60], + [57, 65, 65, 70, 72, 65, 51], + [55, 54, 60, 53, 59, 57, 61], + [65, 56, 55, 52, 55, 62, 57], +]; + +const averageDailyTemperature = (weather) => { + // Solution code here... +} + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 6 +// +// Write a function named lowestWeeklyAverage that accepts a two-dimensional array +// of daily temperatures grouped week-by-week. +// Calculate the average temperature for each week and return the value of +// the lowest weekly average temperature. +// +// For example, in the data set below, the lowest weekly average temperature should be 46. +// ------------------------------------------------------------------------------------------------ + +let lowestWeeklyTemperatureData = [ + [33, 64, 58, 65, 71, 57, 60], + [40, 45, 33, 53, 44, 59, 48], + [55, 54, 60, 53, 59, 57, 61], + [65, 56, 55, 52, 55, 62, 57], +]; + +const lowestWeeklyAverage = (weather) => { + // Solution code here... +} + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 7 +// +// Write a function called excel that accepts a string representing rows and columns. +// Rows are seperated by newline "\n" characters. Columns are seperated by spaces. +// You should parse the string as rows and columns and compute the sum of the values for each row. +// Return an array with the sum of the values in each row. +// +// Here's an algorithm you can use: +// +// create an empty array to store the sum value of each row +// split the input string on newline "\n" characters +// +// use a for loop to iterate over each row +// initialize a variable to store the row sum as zero +// split the row string on commas "," to get an array of column values +// use a for loop to iterate over each column value +// use parseInt() to convert each column string to a number +// add the number to the total for the row +// push the row total onto the very first array +// return the array with all the row sums +// +// Here is a sample data set: '1,1,1\n4,4,4\n9,9,9' +// ------------------------------------------------------------------------------------------------ + +const excel = (str) => { + // Solution code here... +} + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 8 +// +// Write a function named detectTicTacToeWin that accepts a 2D array of strings. Each string is +// guaranteed to be either "X", "O" or an empty string. Your function should check to see if +// any row, column, or either diagonal has three matching "X" or "O" symbols (non-empty strings) +// three-in-a-line. Your function should return either true or false to indicate if +// someone won the game. +// +// Instead of trying to write crazy for loops to automate checking the rows, columns and diagonals +// consider writing one helper function that accepts three coordinate pairs and checks the values +// of the array at those locations. For instance helpCheck(row1, col1, row2, col2, row3, col3). +// Writing that helpCheck function to check evey possible win line is way easier than writing for loops! +// +// Here is a sample board: +// [ +// ['X', '', 'O'], +// ['X', 'O', ''], +// ['X', 'O', 'X'], +// ]; +// ------------------------------------------------------------------------------------------------ + +const detectTicTacToeWin = (board) => { + // Solution code here... +} + +// ------------------------------------------------------------------------------------------------ +// CHALLENGE 9 +// +// Write a function called minesweeper that accepts a 2D array representing a game of minesweeper. +// The function should create a new array the same size as the initial array. Do not modify the original array. +// +// Each cell contains only either `null` or the string "*" to represent a bomb. +// Your function should return a 2D array where each cell is a number that represents +// how many bombs that cells is touching. +// Cells that do not touch any bomb should contain a zero. +// Cells that contain a bomb themselves should contain a 9. +// +// Consider writing a helper function getCellValue(arr, row, col) that returns either the value at the +// cell or `null` if the value is out of the bounds of the array (going off the top, bottom, left or right). +// This helper function allows you easier iterate through the 2D array checking surrounding cells from +// one cell location without worrying about accessing things outside of the array. +// +// Here is a sample board: +// [ +// [ null, null, null, null, '*' ], +// [ null, null, null, null, '*' ], +// [ '*', null, null, null, null ], +// [ null, null, null, '*', null ], +// [ null, '*', null, null, null ], +// ]; +// ------------------------------------------------------------------------------------------------ + +const minesweeper = (board) => { + // Solution code here... +} + +// ------------------------------------------------------------------------------------------------ +// TESTS +// +// All the code below will verify that your functions are working to solve the challenges. +// +// DO NOT CHANGE any of the below code. +// +// Run your tests from the console: jest challenge-03.test.js +// +// ------------------------------------------------------------------------------------------------ + +describe('Testing challenge 1', () => { + test('It should return the number 14', () => { + expect(findFourteen(nestedArray)).toStrictEqual(14); + }); + test('It should also work for other input arrays', () => { + expect(findFourteen([[], [], [[0,1,2]]])).toStrictEqual(1); + }) +}); + +describe('Testing challenge 2', () => { + test('It should return the number 24', () => { + expect(howManyTreats(errands)).toStrictEqual(24); + }); + test('It should also work for other arrays of objects', () => { + expect(howManyTreats([0,0,{items: [0, {quantity: 7}]}])).toStrictEqual(7); + }) +}); + +describe('Testing challenge 3', () => { + const battleshipData = [ + ['#', ' ', '#', ' '], + ['#', ' ', '#', ' '], + ['#', ' ', ' ', ' '], + [' ', ' ', '#', '#'], + ]; + + test('It should return "hit" when it hits a boat', () => { + expect(battleship(battleshipData, 0, 0)).toStrictEqual('hit'); + expect(battleship(battleshipData, 1, 0)).toStrictEqual('hit'); + }); + + test('It should return "miss" when it doesn\'t hit a boat', () => { + expect(battleship(battleshipData, 0, 1)).toStrictEqual('miss'); + expect(battleship(battleshipData, 3, 0)).toStrictEqual('miss'); + }); +}); + +describe('Testing challenge 4', () => { + test('It should multiply all the numbers together', () => { + expect(calculateProduct([[1,2], [3,4], [5,6]])).toStrictEqual(720); + }); + + test('It should return zero if there are any zeroes in the data', () => { + expect(calculateProduct([[2, 3, 4, 6, 0], [4, 3, 7], [2, 4, 6]])).toStrictEqual(0); + }); + test('It should work even if some of the arrays contain no numbers', () => { + expect(calculateProduct([[1,2], [], [3,4,5]])).toStrictEqual(120); + }); +}); + +describe('Testing challenge 5', () => { + test('It should calculate and return the average temperature of the data set', () => { + expect(averageDailyTemperature(weeklyTemperatures)).toStrictEqual(60.25); + }); +}); + +describe('Testing challenge 6', () => { + test('It should return the lowest weekly average temperature within the data set', () => { + expect(lowestWeeklyAverage(weeklyTemperatures)).toStrictEqual(57); + expect(lowestWeeklyAverage(lowestWeeklyTemperatureData)).toStrictEqual(46); + }); +}); + +describe('Testing challenge 7', () => { + test('It should return the total count for each row', () => { + let result = excel('1,1,1\n4,4,4\n9,9,9'); + expect(result.length).toStrictEqual(3); + expect(result[0]).toStrictEqual(3); + expect(result[1]).toStrictEqual(12); + expect(result[2]).toStrictEqual(27); + }); +}); + +describe('Testing challenge 8', () => { + test('It should return true if there are three in a row', () => { + expect(detectTicTacToeWin([ ['X', '', 'O'], ['X', 'O', ''], ['X', 'O', 'X'] ])).toStrictEqual(true); + expect(detectTicTacToeWin([ ['O', '', 'X'], ['X', 'O', 'X'], ['X', '', 'O']])).toStrictEqual(true); + }); + + test('It should return false if there are not three in a row', () => { + expect(detectTicTacToeWin([ ['X', '', 'O'], ['O', 'O', ''], ['X', 'O', 'X'] ])).toStrictEqual(false); + }); +}); + +describe('Testing challenge 9', () => { + test('It should return the number of adjacent bombs', () => { + const minefield = + [ [ null, null, null, null, '*' ], + [ null, null, null, null, '*' ], + [ '*', null, null, null, null ], + [ null, null, null, '*', null ], + [ null, '*', null, null, null ] ]; + const expected = + [ [0, 0, 0, 2, 9], + [1, 1, 0, 2, 9], + [9, 1, 1, 2, 2], + [2, 2, 2, 9, 1], + [1, 9, 2, 1, 1] ]; + expect(minesweeper(minefield)).toStrictEqual(expected); + }); +}); \ No newline at end of file