diff --git a/code-challenges/challenges-01.test.js b/code-challenges/challenges-01.test.js deleted file mode 100644 index 4e14a1f..0000000 --- a/code-challenges/challenges-01.test.js +++ /dev/null @@ -1,135 +0,0 @@ -'use strict'; - -/* ------------------------------------------------------------------------------------------------ -CHALLENGE 1 -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) => { - return word.toUpperCase(); -}; - -const speaker = (message, callback) => { - return callback(message); -}; - - -/* ------------------------------------------------------------------------------------------------ -CHALLENGE 2 -Write a function named addValues that takes in an array and a value and pushes the value into the array. This function does not need a return statement. -Then, write a function named addNumbers that takes in four arguments: - - A number to be added to an array - - An array into which the number should be added - - The number of times the number should be added - - A callback function to use to add the numbers to the array (Hint: you already defined it) -Within the addNumbers function, invoke the callback function as many times as necessary, based on the third argument of the addNumbers function. -Return the modified array. ------------------------------------------------------------------------------------------------- */ - -const addValues = (arr, value) => { - arr.push(value); -}; - -const addNumbers = (num, arr, times, callback) => { - for(let i=0; i { - let availableList = []; - availableItems.forEach(item => { - if(item.available === true){ - availableList.push(item.name); - } - - }); - return availableList; -}; - - -/* ------------------------------------------------------------------------------------------------ -CHALLENGE 4 -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. -Return the resulting output array. ------------------------------------------------------------------------------------------------- */ - - -const fizzbuzz = (arr) => { - const outputArray = []; - arr.forEach((num, index) =>{ - if (num % 3 === 0 && num % 5 === 0) { - outputArray.push('Fizz Buzz'); - } - else if (num % 3 === 0) { - outputArray.push('Fizz'); - } - else if (num % 5 === 0) { - outputArray.push('Buzz'); - } - else { - outputArray.push(num); - } - }); - return outputArray; -} - -/* ------------------------------------------------------------------------------------------------ -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-01.test.js ------------------------------------------------------------------------------------------------- */ - -describe('Testing challenge 1', () => { - test('It should return the message with all uppercase characters', () => { - expect(speaker('hello 301 students!', greeting)).toStrictEqual('HELLO 301 STUDENTS!'); - }); -}); - -describe('Testing challenge 2', () => { - test('It should add the number 8 to the array five times', () => { - expect(addNumbers(8, [], 5, addValues)).toStrictEqual([8, 8, 8, 8, 8]); - expect(addNumbers(8, [], 5, addValues).length).toStrictEqual(5); - }); -}); - -describe('Testing challenge 3', () => { - 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']); - expect(createList(inventory).length).toStrictEqual(3); - }); -}); - -describe('Testing challenge 4', () => { - const inputs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; - - test('It should print out messages or numbers', () => { - expect(fizzbuzz(inputs)).toStrictEqual([1, 2, 'Fizz', 4, 'Buzz', 'Fizz', 7, 8, 'Fizz', 'Buzz', 11, 'Fizz', 13, 14, 'Fizz Buzz', 16]); - expect(fizzbuzz(inputs).length).toStrictEqual(16); - }); -}); diff --git a/code-challenges/challenges-02.test.js b/code-challenges/challenges-02.test.js deleted file mode 100644 index a202140..0000000 --- a/code-challenges/challenges-02.test.js +++ /dev/null @@ -1,181 +0,0 @@ -'use strict'; - -/* ------------------------------------------------------------------------------------------------ - -CHALLENGE 1 - Review - -Write a function named raisedToTheThird that takes in an array of numbers and returns a new array of each of those numbers raised to the 3rd power (hint: look up Math.pow()). Use forEach to solve this problem. - ------------------------------------------------------------------------------------------------- */ - -const raisedToTheThird = (arr) => { - // Solution code here... - let result = []; - arr.forEach(item=>{ - result.push(Math.pow(item,3)) - }) - return result - -} - -/* ------------------------------------------------------------------------------------------------ -CHALLENGE 2 - -Write a function that appends ' The end.' to a string, and returns the modified string. The original source string should not be modified. - ------------------------------------------------------------------------------------------------- */ - -const appendTheEnd = (str) => { - // Solution code here... - return `${str} The end.`; - - -}; - -/* ------------------------------------------------------------------------------------------------ -CHALLENGE 3 - -Write a function that accepts an array and copies the first element to the end of the array. The change should be reflected in the source array that was passed in to the function. That is, the function should modify the array 'in place'. - -Do not use a return statement. - -For example: -const a = [1, 2, 3]; -appendFirstToLast(a); -console.log(a) prints [1, 2, 3, 1] ------------------------------------------------------------------------------------------------- */ - -const appendFirstToLast = (arr) => { - // Solution code here... - arr.push(arr[0]); - -}; - -/* ------------------------------------------------------------------------------------------------ -CHALLENGE 4 - -Write a function that accepts an object and an integer as arguments and adds a new property to the object called yearBorn. The value of the yearBorn property should be the integer that was passed in. - -The change should be reflected in the source object that was passed in to the function. That is, the function should modify the object 'in place'. - -Do not use a return statement. - -For example: -const octavia = { fullName: 'Octavia Estelle Butler' }; -addBirthYearProperty(octavia, 1947); -console.log(a) prints { fullName: 'Octavia Estelle Butler', yearBorn: 1947 } ------------------------------------------------------------------------------------------------- */ - -const addBirthYearProperty = (obj, year) => { - // Solution code here... - obj.yearBorn = year; - -}; - -/* ------------------------------------------------------------------------------------------------ -CHALLENGE 5 - Stretch Goal - -Write a function that accepts an array of people objects and adds a new property called isAuthor to each object in the list. Set the value of the new property to true. - -The function should modify the object in place. Do not use a return statement. - -For example: -const people = [{ fullName: 'Octavia Butler' }, { fullName: 'Ray Bradbury' }]; -setStatusAsAuthor(people); -console.log(people[1].isAuthor) prints true ------------------------------------------------------------------------------------------------- */ - -const setStatusAsAuthor = (people) => { - // Solution code here... - people.forEach(person => { - person.isAuthor = true; - }); -}; - -/* ------------------------------------------------------------------------------------------------ -CHALLENGE 6 - Stretch Goal - -Write a function that accepts two arrays. Append the values from the second array into the first, -maintaining the ordering. - -The function should modify the first array in place. Do not use a return statement. - -For example: -const a = [1, 2]; NOTE: If you assign an array to a `const`, you can't re-assign it later, but you can change the values in the array. -const b = [3, 4]; -append(a, b); -console.log(a) prints [1, 2, 3, 4] ------------------------------------------------------------------------------------------------- */ - -const append = (arr1, arr2) => { - // Solution code here... - arr2.forEach(element => arr1.concat(element)); - - -}; - -/* ------------------------------------------------------------------------------------------------ -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 return a new array of numbers raised to the thrid power', () => { - expect(raisedToTheThird([2, 4, 5, -7, 0])).toStrictEqual([8, 64, 125, -343, 0]); - }); -}); - -describe('Testing challenge 2', () => { - test('It should append without modifying the oiginal', () => { - const a = 'This is my story.'; - const b = appendTheEnd(a); - - expect(a).toStrictEqual('This is my story.'); - expect(b).toStrictEqual('This is my story. The end.'); - }); -}); - -describe('Testing challenge 3', () => { - test('It should append by modifying the oiginal', () => { - const a = ['Yes', 'it', 'is']; - appendFirstToLast(a); - - expect(a).toStrictEqual(['Yes', 'it', 'is', 'Yes']); - }); -}); - -describe('Testing challenge 4', () => { - test('It should add a property to an object', () => { - const a = { fullName: 'Octavia Butler' }; - addBirthYearProperty(a, 1947); - - expect(a.yearBorn).toStrictEqual(1947); - }); -}); - -xdescribe('Testing challenge 5', () => { - test('It should add a property to every object in an array', () => { - const a = [{ fullName: 'Octavia Butler' }, { fullName: 'Ray Bradbury' }, { fullName: 'Kurt Vonnegut' }]; - setStatusAsAuthor(a); - - expect(a[0].isAuthor).toStrictEqual(true); - expect(a[1].isAuthor).toStrictEqual(true); - expect(a[2].isAuthor).toStrictEqual(true); - }); -}); - -xdescribe('Testing challenge 6', () => { - test('It should append the second array to the first', () => { - const a = [1, 2, 3, 4]; - const b = [5, 6, 7, 8]; - append(a, b); - - expect(a).toStrictEqual([1, 2, 3, 4, 5, 6, 7, 8]); - }); -}); diff --git a/code-challenges/challenges-03.test.js b/code-challenges/challenges-03.test.js deleted file mode 100644 index 36d6908..0000000 --- a/code-challenges/challenges-03.test.js +++ /dev/null @@ -1,515 +0,0 @@ -'use strict'; - -// to learn more about the cheerio library and what it is doing, look at their documentation: https://www.npmjs.com/package/cheerio -const cheerio = require('cheerio'); - -/* ------------------------------------------------------------------------------------------------ -CHALLENGE 1 - Review - -Write a function named changeAllClassNames that uses jQuery to select all each li and add a class of "fruit"; - ------------------------------------------------------------------------------------------------- */ -let $ = createSnippetWithJQuery(` - -`); - -const changeAllClassNames = () => { - // Solution code here... - $('li').addClass('fruit'); - -}; - -/* ------------------------------------------------------------------------------------------------ -CHALLENGE 2 - -Write a function named sortBackwards that takes in an array of numbers and returns the same array, with the numbers sorted, highest to smallest. ------------------------------------------------------------------------------------------------- */ - -const sortBackwards = (arr) => { - // Solution code here... - arr.sort((a, b) =>{ - return (b-a); - }); - return arr; -}; - -/* ------------------------------------------------------------------------------------------------ -CHALLENGE 3 - -Write a function named alphabetize that takes in an array of strings and returns the same array with the strings sorted alphabetically. - -In this alphabetization, capital letters come before lower case letters. - -For example, ['Alphabet', 'Zebra', 'alphabet', 'carrot'] is correctly sorted. ------------------------------------------------------------------------------------------------- */ - -const alphabetize = (arr) => { - // Solution code here... - arr.sort((a, b) =>{ - if(a > b){ - return 1; - }else if (a < b){ - return ; - } - }); - return arr; -}; - -/* ------------------------------------------------------------------------------------------------ -CHALLENGE 4 - -Write a function named sortByLength that takes in an array of strings and returns the same array, with the strings sorted by their length, lowest to highest. ------------------------------------------------------------------------------------------------- */ - -const sortByLength = (arr) => { - // Solution code here... - arr.sort((a, b) => { - return a.length - b.length - }) - return arr; -}; - - -/* ------------------------------------------------------------------------------------------------ -CHALLENGE 5 - Stretch Goal - -Write a function named alphabetizeBetter that takes in an array of strings and returns the same array, with the strings sorted alphabetically. Capitalization should not change the sort order of two strings. - -For example, ['Alphabet', 'alphabet', 'carrot', 'Zebra'] is correctly sorted, and so is ['alphabet', 'Alphabet', 'carrot', 'Zebra']. ------------------------------------------------------------------------------------------------- */ - -const alphabetizeBetter = (arr) => { - // Solution code here... - arr.sort((a, b) => { - if (a.toLowerCase() < b.toLowerCase()) { - return -1; - } else if (a.toLowerCase() > b.toLowerCase()) { - return 1; - } else { - return 0; - } - }); - - return arr; -}; - -/* ------------------------------------------------------------------------------------------------ -CHALLENGE 6 - Stretch Goal - -Write a function named sortByPrice that takes in an array of objects, each of which has a 'price' property, and sorts those objects by price, lowest to highest, returning the same array. - -Here is an example of the input: -[ - {name: 'Sweatshirt', price: 45}, - {name: 'Bookmark', price: 2.50}, - {name: 'Tote bag', price: 15} -]; ------------------------------------------------------------------------------------------------- */ - -const sortByPrice = (arr) => { - // Solution code here... - arr.sort((a, b) => { - if (a.price < b.price) { - return -1; - } else if (a.price > b.price) { - return 1; - } else { - return 0; - } - }); - - return arr; -}; - -/* ------------------------------------------------------------------------------------------------ -CHALLENGE 7 - Stretch Goal - -Write a function named sortNumbersByLength that takes in an array of numbers and sorts those numbers by their length. - -For example, [1, 14, 0.2, -281, 54782] is only correctly sorted in that order. ------------------------------------------------------------------------------------------------- */ - -const sortNumbersByLength = (arr) => { - // Solution code here... - arr.sort((a, b) =>{ - return a.length > b.length ? 1 : -1; - }) -}; - -/*----------------------------------------------------------------------------------------------- -CHALLENGE 8 - Stretch Goal - -Write a function named sortPeople that takes in an array of Person objects, each of which has firstName, lastName, and age properties, and sorts those people by their last names. Do not worry about capitalization or first names. ------------------------------------------------------------------------------------------------- */ - -function Person(firstName, lastName, age) { - this.firstName = firstName; - this.lastName = lastName; - this.age = age; -} - -const people = [ - new Person('Wes', 'Washington', 25), - new Person('Casey', 'Codefellow', 38), - new Person('Stan', 'Seattle', 67), -]; - -const sortPeople = (arr) => { - // Solution code here... - people.sort((a, b) => { - return a.name > b.name ? 1 : -1; - }) -}; - -/* ------------------------------------------------------------------------------------------------ -CHALLENGE 9 - Stretch Goal - -Write a function named sortPeopleBetter that takes in an array of Person objects, each of which has firstName, lastName, and age properties, and sorts those people by their last names. - -If two people share the same last name, alphabetize on their first name. - -If two people have the same full name, the younger one should come first. Do not worry about capitalization. ------------------------------------------------------------------------------------------------- */ - -const sortPeopleBetter = (arr) => { - // Solution code here... - arr.sort((a, b) => { - if (a.lastName < b.lastName) { - return -1; - } else if (a.lastName > b.lastName) { - return 1; - } else if (a.lastName === b.lastName) { - if (a.firstName < b.firstName) { - return -1; - } else if (a.firstName > b.firstName) { - return 1; - } else if (a.firstName === b.firstName) { - if (a.age < b.age) { - return -1; - } else if (a.age > b.age) { - return 1; - } - else { - return 0; - } - } - } - }); - - return arr; -}; - -/* ------------------------------------------------------------------------------------------------ -CHALLENGE 10 - Stretch Goal - -Write a function named sortMeetingsByDay that takes in an array of objects, each of which represents a meeting happening a particular day of the week, with a particular start time and end time. - -Sort the meetings by the day on which they happen, Monday-Friday. It does not matter which order meetings come in on a particular day. For example, if there are two meetings on Monday, it does not matter which comes first. ------------------------------------------------------------------------------------------------- */ - -function Meeting(dayOfWeek, start, end) { - this.dayOfWeek = dayOfWeek; - this.start = start; - this.end = end; -} -const meetings = [ - new Meeting('Monday', '0900', '1000'), - new Meeting('Wednesday', '1300', '1500'), - new Meeting('Tuesday', '1145', '1315'), - new Meeting('Wednesday', '0930', '1000'), - new Meeting('Monday', '0900', '0945'), - new Meeting('Friday', '1200', '1345'), -]; - -const sortMeetingsByDay = (arr) => { - // Solution code here... - function checkWeekDay(day1, day2) { - - // array to reference order of weekdays - let weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']; - - // iterating over weekdays - for (let i = 0; i < weekdays.length; i++) { - - // set current index equal to day1 - if (day1 === weekdays[i]) { - - // iterate again over weekdays - for (let j = 0; j < weekdays.length; j++) { - - // set current index equal to day2 - if (day2 === weekdays[j]) { - - // compare each index once days are referenced against array to check for the days' order - if (i < j) { - return -1; - } - else if (i > j) { - return 1; - } - else { - return 0; - } - } - } - } - } - } - // given a and b days of the week, - arr.sort((a, b) => { - // do this function that checks: - return checkWeekDay(a.dayOfWeek, b.dayOfWeek); - // if a comes before b in the week, - // do not switch the items, - // else if a comes after b in the week, - // switch the items, - // else (if a is b in the week), - // do not switch the items - }); - - return arr; -}; - -/* ------------------------------------------------------------------------------------------------ -CHALLENGE 11 - Stretch Goal - -This challenge should use the array of meetings from challenge 9, above. - -Sort the meetings in the order that they start. If two meetings start at the same time on the same day, the shorter meeting should come first. - -You DO NOT need to use your solution to Challenge 9 in completing Challenge 10. ------------------------------------------------------------------------------------------------- */ - -const sortSchedule = (arr) => { - // Solution code here... - function sortWeekDay(day1, day2) { - - // array to reference order of weekdays - let weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']; - - // iterating over weekdays - for (let i = 0; i < weekdays.length; i++) { - - // set current index equal to day1 - if (day1 === weekdays[i]) { - - // iterate again over weekdays - for (let j = 0; j < weekdays.length; j++) { - - // set current index equal to day2 - if (day2 === weekdays[j]) { - - // compare each index once days are referenced against array to check for the days' order - if (i < j) { - return -1; - } - else if (i > j) { - return 1; - } - else { - return 0; - } - } - } - } - } - } - - function sortTiming(weekDaysSorted) { - weekDaysSorted.sort((a, b) => { - if (a.start < b.start) { - return -1; - } else if (a.start > b.start) { - return 1; - } else if (a.start === b.start) { - if ((a.end - a.start) < (b.end - b.start)) { - return -1; - } else if ((a.end - a.start) > (b.end - b.start)) { - return 1; - } else { - return 0; - } - } - }); - } - - let sortedWeekDays = arr.sort((a, b) => { - return sortWeekDay(a.dayOfWeek, b.dayOfWeek); - }); - - arr = sortTiming(sortedWeekDays); - - return arr; - -}; - -/* ------------------------------------------------------------------------------------------------ -CHALLENGE 12 - Stretch Goal - -Without altering the html, write a function named addPearClass that uses jQuery to add a class of "pear" to the third li. ------------------------------------------------------------------------------------------------- */ -$ = createSnippetWithJQuery(` - -`); - -const addPearClass = () => { - // 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-03.test.js ------------------------------------------------------------------------------------------------- */ - - -describe('Testing challenge 1', () => { - test('It should add a class of fruit to all the list items', () => { - changeAllClassNames(); - - expect($('li.apple').hasClass('fruit')).toBe(true); - expect($('li.orange').hasClass('fruit')).toBe(true); - }); -}); - -describe('Testing challenge 2', () => { - test('It should sort high-to-low the numbers in an array', () => { - const nums = [3,4,5,6,7]; - expect(sortBackwards(nums)).toStrictEqual([7,6,5,4,3]); - expect(sortBackwards([3,2,1])).toStrictEqual([3,2,1]); - expect(sortBackwards([12,20,3])).toStrictEqual([20, 12, 3]); - expect(sortBackwards([])).toStrictEqual([]); - expect(sortBackwards([1])).toStrictEqual([1]); - }); -}); - -describe('Testing challenge 3', () => { - test('It should sort strings alphabetically', () => { - expect(alphabetize(['alphabet', 'Zebra', 'Alphabet', 'carrot'])).toStrictEqual([ 'Alphabet', 'Zebra', 'alphabet', 'carrot']); - expect(alphabetize(['alphabet','Alphabet', 'carrot'])).toStrictEqual([ 'Alphabet', 'alphabet', 'carrot']); - expect(alphabetize([])).toStrictEqual([]); - }); -}); - -describe('Testing challenge 4', () => { - test('It should sort strings by length', () => { - const ans = sortByLength(['alphabet', 'Zebra', 'Alphabet', 'carrot']); - expect(ans.slice(0,2)).toStrictEqual(['Zebra', 'carrot']); - expect(ans.slice(2,4)).toEqual(expect.arrayContaining(['Alphabet', 'alphabet'])); - expect(sortByLength(['a', 'bc', ''])).toStrictEqual(['', 'a', 'bc']); - expect(sortByLength(['a'])).toStrictEqual(['a']); - expect(sortByLength([])).toStrictEqual([]); - }); -}); - -describe('Testing challenge 5', () => { - test('It should alphabetize without regard to capitalization', () => { - expect(alphabetizeBetter(['Alice', 'apple', 'alert', 'Average'])).toStrictEqual([ 'alert', 'Alice', 'apple', 'Average' ]); - const ans = alphabetizeBetter(['alphabet', 'Zebra', 'Alphabet', 'carrot']); - expect(ans.slice(0,2)).toEqual(expect.arrayContaining([ 'Alphabet','alphabet'])); - expect(ans.slice(2)).toStrictEqual(['carrot', 'Zebra']); - }); -}); - -describe('Testing challenge 6', () => { - test('It should sort items by their price', () => { - expect(sortByPrice([ - {name: 'Sweatshirt', price: 45}, - {name: 'Bookmark', price: 2.50}, - {name: 'Tote bag', price: 15} - ])).toStrictEqual([ - {name: 'Bookmark', price: 2.50}, - {name: 'Tote bag', price: 15}, - {name: 'Sweatshirt', price: 45}, - ]); - expect(sortByPrice([{price: 12}, {price: 10}])).toStrictEqual([{price: 10}, {price: 12}]); - expect(sortByPrice([])).toStrictEqual([]); - }); -}); - -describe('Testing challenge 7', () => { - test('It should sort numbers by their length', () => { - expect(sortNumbersByLength([10, 2.8, 1, -47.75])).toStrictEqual([1, 10, 2.8, -47.75]); - expect(sortNumbersByLength([100, 2.82, 1, -47.75])).toStrictEqual([1, 100, 2.82, -47.75]); - expect(sortNumbersByLength([1,2,3])).toEqual(expect.arrayContaining([1,2,3])); - }); -}); - -describe('Testing challenge 8', () => { - test('It should sort people by their last names', () => { - expect(sortPeople(people)).toStrictEqual([ - new Person('Casey', 'Codefellow', 38), - new Person('Stan', 'Seattle', 67), - new Person('Wes', 'Washington', 25), - ]); - expect(sortPeople([{lastName: 'banana'}, {lastName: 'apple'}])) - .toStrictEqual([{lastName: 'apple'}, {lastName: 'banana'}]); - }); -}); - -describe('Testing challenge 9', () => { - test('It should sort people with more strict ordering', () => { - const family = [ - new Person('Casey', 'Codefellows', 55), - new Person('Casey', 'Codefellows', 37), - new Person('Charlie', 'Codefellows', 21), - new Person('Charles', 'Codefellows', 29), - new Person('Carol', 'Codefellow', 88), - ]; - expect(sortPeopleBetter(family)).toStrictEqual([ - new Person('Carol', 'Codefellow', 88), - new Person('Casey', 'Codefellows', 37), - new Person('Casey', 'Codefellows', 55), - new Person('Charles', 'Codefellows', 29), - new Person('Charlie', 'Codefellows', 21), - ]); - expect(sortPeopleBetter([{firstName: 'andrew', lastName: 'apple'}, {firstName: 'andre', lastName: 'apple'}])) - .toStrictEqual([{firstName: 'andre', lastName: 'apple'}, {firstName: 'andrew', lastName: 'apple'}]); - }); -}); - -describe('Testing challenge 10', () => { - test('It should sort meetings by the day on which they happen', () => { - const sortedMeetings = sortMeetingsByDay(meetings); - expect(sortedMeetings.slice(0,2)).toEqual(expect.arrayContaining([new Meeting('Monday', '0900', '0945'), new Meeting('Monday', '0900', '1000')])); - expect(sortedMeetings[2]).toStrictEqual(new Meeting('Tuesday', '1145', '1315')); - expect(sortedMeetings.slice(3,5)).toEqual(expect.arrayContaining([new Meeting('Wednesday', '0930', '1000'), new Meeting('Wednesday', '1300', '1500')])); - expect(sortedMeetings[5]).toStrictEqual(new Meeting('Friday', '1200', '1345')); - }); -}); - -describe('Testing challenge 11', () => { - test('It should sort meetings by when they happen', () => { - expect(sortSchedule(meetings)).toStrictEqual([ - new Meeting('Monday', '0900', '0945'), - new Meeting('Monday', '0900', '1000'), - new Meeting('Tuesday', '1145', '1315'), - new Meeting('Wednesday', '0930', '1000'), - new Meeting('Wednesday', '1300', '1500'), - new Meeting('Friday', '1200', '1345'), - ]); - }); -}); - -xdescribe('Testing challenge 12', () => { - test('It should add a class of pear to the thrid li', () => { - addPearClass(); - expect($('li:nth-child(3)').hasClass('pear')).toBe(true); - }); -}); - -function createSnippetWithJQuery(html){ - return cheerio.load(html); -} diff --git a/code-challenges/challenges-04.test.js b/code-challenges/challenges-04.test.js deleted file mode 100644 index d326892..0000000 --- a/code-challenges/challenges-04.test.js +++ /dev/null @@ -1,276 +0,0 @@ -'use strict'; - -// to learn more about the cheerio library and what it is doing, look at their documentation: https://www.npmjs.com/package/cheerio -const cheerio = require('cheerio'); - -/* ------------------------------------------------------------------------------------------------ -CHALLENGE 1 - Review - -Without altering the html, write a function named generateSubmitButton that uses jQuery to create a submit button with the text "submit" and append it to the DOM. ------------------------------------------------------------------------------------------------- */ -let $ = createSnippetWithJQuery(` -
-
- - - -
-
-`); - -const generateSubmitButton = () => { - // Solution code here... - $('section').append(``); - -} - -/* ------------------------------------------------------------------------------------------------ -CHALLENGE 2 - -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. - -For example: -12345 returns true -'12345' returns true -'h3llo world' returns true -'hello world' returns false ------------------------------------------------------------------------------------------------- */ - -const isNum = (input) => { - // Solution code here... - let regex = /\d/gm; - if (regex.test(input)) { - return true; - } else { - return false; - } -}; - -/* ------------------------------------------------------------------------------------------------ -CHALLENGE 3 - -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. It should only match words, not punctuation. - -Return an array containing all the matches. ------------------------------------------------------------------------------------------------- */ - -const isCapitalized = (str) => { - // Solution code here... - let empty = []; - let regex = /\b[A-Z]\w*\b/mg; - if (str.match(regex) === null) { - return empty; - } else { - return str.match(regex); - } -}; - -/* ------------------------------------------------------------------------------------------------ -CHALLENGE 4 - -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 = (arr) => { - // Solution code here... - let newArr = []; - arr.forEach((city) => { - let regex = /^[A-J]\w*/gm; - if (regex.test(city)) { - newArr.push(city); - } - }); - return newArr; -}; - -/* ------------------------------------------------------------------------------------------------ -CHALLENGE 5 - Stretch Goal - -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... - let regex = /^[Oo]ct(ober)*$/gm; - if (regex.test(input)) { - return true; - } else { - return false; - } -}; - -/* ------------------------------------------------------------------------------------------------ -CHALLENGE 6 - Stretch Goal - -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. The word "day!" would not be returned because it is immediately followed by an exclamation point. - -The expected output of "Hello, and have a wonderful day!" is ["and ", "have ", "a ", "wonderful "]. ------------------------------------------------------------------------------------------------- */ - -const noPunctuation = str => { - // Solution code here... - let regex = /\b\w*\s/gm; - return str.match(regex); -}; - -/* ------------------------------------------------------------------------------------------------ -CHALLENGE 7 - Stretch Goal - -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, regardless of capitalization, and replace them with an underscore. - -The function should return a string containing the consonants in their original positions 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... - let regex = /[a,e,i,o,u]/gmi; - return str.replace(regex, '_'); -}; - -/* ------------------------------------------------------------------------------------------------ -CHALLENGE 8 - Stretch Goal - -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 = (str) => { - // 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 add a submit button to the DOM', () => { - generateSubmitButton(); - expect($('button').text()).toStrictEqual('submit'); - }) -}); - -describe('Testing challenge 2', () => { - 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 3', () => { - 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); - - expect(isCapitalized('Given by our hand in the meadow that is called Runnymede, between Windsor and Staines, on the fifteenth day of June in the seventeenth year of our reign (i.e. 1215: the new regnal year began on 28 May).')).toStrictEqual(['Given', 'Runnymede', 'Windsor', 'Staines', 'June', 'May']); - - expect(isCapitalized('these words are all failures')).toStrictEqual([]); - }); -}); - -describe('Testing challenge 4', () => { - 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); - - expect(citiesAtoJ([])).toStrictEqual([]); - expect(citiesAtoJ(['Albuquerque', 'Chicago', 'Philadelphia', 'Newark', 'Sacramento', 'Eugene'])).toEqual(expect.arrayContaining(['Albuquerque', 'Chicago', 'Eugene'])); - }); - - 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 5', () => { - 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 6', () => { - 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); - expect(noPunctuation('Given by our hand in the meadow that is called Runnymede, between Windsor and Staines, on the fifteenth day of June in the seventeenth year of our reign (i.e. 1215: the new regnal year began on 28 May).')).toEqual(expect.arrayContaining(['Given ', 'by ', 'our ', 'hand ', 'in ', 'the ', 'meadow ', 'that ', 'is ', 'called ', 'between ', 'Windsor ', 'and ', 'on ', 'the ', 'fifteenth ', 'day ', 'of ', 'June ', 'in ', 'the ', 'seventeenth ', 'year ', 'of ', 'our ', 'reign ', 'the ', 'new ', 'regnal ', 'year ', 'began ', 'on ', '28 '])); - }); - - 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 7', () => { - 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!'); - expect(hangman('I wAnt them all tO bE removed and replaced with Underscores.')).toStrictEqual('_ w_nt th_m _ll t_ b_ r_m_v_d _nd r_pl_c_d w_th _nd_rsc_r_s.'); - }); - - test('It should not contain the letters "a", "e", "i", "o", or "u"', () => { - expect(hangman(startString)).not.toContain('a', 'e', 'i', 'o', 'u'); - }); -}); - -xdescribe('Testing challenge 8', () => { - 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); - }); -}); - -function createSnippetWithJQuery(html){ - return cheerio.load(html); -}; diff --git a/code-challenges/challenges-05.test.js b/code-challenges/challenges-05.test.js deleted file mode 100644 index 8ba0125..0000000 --- a/code-challenges/challenges-05.test.js +++ /dev/null @@ -1,403 +0,0 @@ -'use strict'; - -// to learn more about the cheerio library and what it is doing, look at their documentation: https://www.npmjs.com/package/cheerio -const cheerio = require('cheerio'); - -/* ------------------------------------------------------------------------------------------------ -CHALLENGE 1 - Review - -Write a function named templateWithJQuery that uses jQuery to get the html template from the DOM, copy the contents, fill it with the Star Wars People, and append it to the DOM. ------------------------------------------------------------------------------------------------- */ -let starWarsPeople = [ - { - "name": "Luke Skywalker", - "height": "172", - "eye_color": "blue" - }, - { - "name": "C-3PO", - "height": "167", - "eye_color": "yellow" - }, - { - "name": "R2-D2", - "height": "96", - "eye_color": "red" - } -]; - -let $ = createSnippetWithJQuery(` -
-
-

-

-

-
-
-`); - -const templateWithJQuery = () => { - // Solution code here... - starWarsPeople.forEach(value => { - const myTemplate = $('#template').html(); - const $section = $('
'); - $section.html(myTemplate); - $section.find('h2').text(value.name); - $section.find('h3').text(value.height); - $section.find('p').text(value.eye_color); - $('main').append($section); - }) -} - -/* ------------------------------------------------------------------------------------------------ -CHALLENGE 2 - -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 = (str) => { - let result = []; - // Solution code here... - for (let i = 0; i <= str.length; i++) { - let iteration = str.slice(i, str.length); - result.push(iteration); - } - return result; -}; - -/* ------------------------------------------------------------------------------------------------ -CHALLENGE 3 - -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 = (arr) => { - // Solution code here... - let result = []; - for (let i = 0; i < arr.length; i++) { - result.push(arr[i]); - } - return result; -}; - - -/* ------------------------------------------------------------------------------------------------ -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... - let food = ''; - recipe.ingredients.forEach((ingredient) => { - let counter = 2; - for (let letter = 0; letter < ingredient.length; letter++) { - if (counter > 0) { - if (ingredient[letter] === ' ') { - counter--; - food = ingredient.slice(letter + 1); - } - } - } - result.push(food); - }); - return result; -}; - -/* ------------------------------------------------------------------------------------------------ -CHALLENGE 5 - Stretch Goal - -Write a function named splitFoods that uses split to produce the same output as Challenge 3. - -You may also use other string or array methods. ------------------------------------------------------------------------------------------------- */ - -const splitFoods = (recipe) => { - // let result = []; - // // Solution code here... - recipe.ingredients.forEach((ingredient) => { - let food = ''; - let arraySplit = ingredient.split(' '); - let foodArray = arraySplit.slice(2); - foodArray.forEach((word) => { - if (xfood !== '') { - food += ' '; - } - food += word; - }); - result.push(food); - }); - return result; -}; - -/* ------------------------------------------------------------------------------------------------ -CHALLENGE 6 - Stretch Goal - -Use the same recipe from Challenge 3, above. - -Write a function named stepAction that takes in the recipe and extracts the action verbs from the steps. Fortunate for you, the action verbs are the first word of each action. - -Return a new array containing just the verbs. For example, ['Mix until evenly distributed'] returns ['Mix']. ------------------------------------------------------------------------------------------------- */ - -const stepActions = (recipe) => { - let result = []; - // Solution code here... - recipe.steps.forEach((step) => { - let split = step.split(' '); - let verbArray = split.slice(0, 1); - let verb = verbArray.toString(); - result.push(verb); - }); - return result; -}; - -/* ------------------------------------------------------------------------------------------------ -CHALLENGE 7 - Stretch Goal - -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: - const integers = [1, 2, 3, 4, 5, 6]; - removeEvenValues(integers); - console.log(integers) will print [1, 3, 5] ------------------------------------------------------------------------------------------------- */ - -const removeEvenValues = (arr) => { - // Solution code here... - console.log('original', arr); - arr.forEach((even) => { - if (even % 2 === 0) { - arr.forEach((number) => { - if (number % 2 === 0) { - arr.splice(arr.indexOf(number), 1); - } - }); - } - }); -}; - -/* ------------------------------------------------------------------------------------------------ -CHALLENGE 8 - Stretch Goal - -Write a function named removeLastCharacters that takes in a string and a number. The numberOfCharacters argument determines how many characters will be removed from the end of the string. Return the resulting string. - -If the numberOfCharacters argument is greater than the length of the input string, the function should return an empty string. - -If the numberOfCharacters argument input is a negative number, the function should return the input string without any changes. - -For example: -removeLastCharacters('Gregor', 2) returns 'Greg' -removeLastCharacters('Gregor', -2) returns 'Gregor' -removeLastCharacters('Gregor', 9) returns '' ------------------------------------------------------------------------------------------------- */ - -const removeLastCharacters = (str, numberOfCharacters) => { - // Solution code here... - -}; - - -/* ------------------------------------------------------------------------------------------------ -CHALLENGE 9 - Stretch Goal - -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 = (str) => { - let total = 0; - // Solution code here... - return total; -}; - - -/* ------------------------------------------------------------------------------------------------ -CHALLENGE 10 - Stretch Goal - -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 = (str) => { - // Solution code here... -}; - -/* ------------------------------------------------------------------------------------------------ -CHALLENGE 11 - Stretch Goal - -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 = (str) => { - // 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 append the star wars people to the DOM', () => { - templateWithJQuery(); - expect($('section:nth-child(2) h2').text()).toStrictEqual('Luke Skywalker'); - expect($('section:nth-child(3) h3').text()).toStrictEqual('167'); - expect($('section:nth-child(4) p').text()).toStrictEqual('red'); - }) -}); - -describe('Testing challenge 2', () => { - 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 3', () => { - 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 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); - }); -}); - -xdescribe('Testing challenge 5', () => { - 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']); - }); -}); - -xdescribe('Testing challenge 6', () => { - 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); - }); -}); - -xdescribe('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); - }); -}); - -xdescribe('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(''); - }); -}); - -xdescribe('Testing challenge 9', () => { - 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); - }); -}); - -xdescribe('Testing challenge 10', () => { - 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'); - }); -}); - -xdescribe('Testing challenge 11', () => { - 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']); - }); -}); - - -function createSnippetWithJQuery(html){ - return cheerio.load(html); -}; \ No newline at end of file diff --git a/code-challenges/challenges-08.test.js b/code-challenges/challenges-08.test.js new file mode 100644 index 0000000..4fbb879 --- /dev/null +++ b/code-challenges/challenges-08.test.js @@ -0,0 +1,329 @@ +'use strict'; + +/* ------------------------------------------------------------------------------------------------ +CHALLENGE 1 - Review + +Write a function named sayHello, that sends the message 'Hello from the back-end' when a user hits the `/hello` route. + +------------------------------------------------------------------------------------------------ */ + +// Express sever here +const createServer = () => { + const express=require('express'); + const app=express(); + app.get('/hello', sayHello); + + var server = app.listen(3301, function () { + var port = server.address().port; + console.log('Example app listening at port', port); + }); + return server; +}; + + +function sayHello(request, response){ + // Solution code here... + response.send('Hello from the back-end'); + +} + +/* ------------------------------------------------------------------------------------------------ +CHALLENGE 2 + +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 = (arr) => { + // Solution code here... + return arr.filter(value =>value %2 !== 0); + +}; + +/* ------------------------------------------------------------------------------------------------ +CHALLENGE 3 + +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 or utilize a regular expression pattern. + +For example, filterStringsWithVowels('gregor','hound','xyz') returns ['gregor', 'hound']. +------------------------------------------------------------------------------------------------ */ + + +const filterStringsWithVowels = (arr) => { + // Solution code here... + let regex = /[aeiou]/g; + return arr.filter(value => value.match(regex)); +}; + + +/* ------------------------------------------------------------------------------------------------ +CHALLENGE 4 + +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, arr) => { + // Solution code here... + return arr.filter(value => !forbiddenValues.includes(value)); + +}; + +/* ------------------------------------------------------------------------------------------------ +CHALLENGE 5 - Stretch Goal + +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 = (arr, minBaseStat) => { + // Solution code here... + return minBaseStat.filter(minBaseStat > arr) + +}; + +/* ------------------------------------------------------------------------------------------------ +CHALLENGE 6 - Stretch Goal + +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 = (arr, minBaseStat) => { + // Solution code here... +}; + +/* ------------------------------------------------------------------------------------------------ +CHALLENGE 7 - Stretch Goal + +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 = (arr) => { + // Solution code here... +}; + +/* ------------------------------------------------------------------------------------------------ +CHALLENGE 8 - Stretch Goal + +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 = (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-08.test.js + +------------------------------------------------------------------------------------------------ */ + +describe('Testing challenge 1', () => { + + const request = require('supertest'); + + let server; + + beforeEach(function () { + server = createServer(); + }); + + afterEach(function () { + server.close(); + }); + + test('responds to /hello', function testSlash(done) { + request(server) + .get('/hello') + .expect(200, done); + }); + test('404 everything else', function testPath(done) { + request(server) + .get('/foo/bar') + .expect(404, done); + }); +}); + +describe('Testing challenge 2', () => { + 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 3', () => { + 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 4', () => { + 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([]); + }); +}); + +xdescribe('Testing challenge 5', () => { + 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}]); + }); +}); + +xdescribe('Testing challenge 6', () => { + 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']); + }); +}); + +xdescribe('Testing challenge 7', () => { + 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); + }); +}); + +xdescribe('Testing challenge 8', () => { + 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']); + }); +}); diff --git a/code-challenges/challenges-09.test.js b/code-challenges/challenges-09.test.js new file mode 100644 index 0000000..fe6ff72 --- /dev/null +++ b/code-challenges/challenges-09.test.js @@ -0,0 +1,536 @@ +'use strict'; + +/* ------------------------------------------------------------------------------------------------ +CHALLENGE 1 - Review + +First, write a function called mapCurrentEvents that maps over the current events object, runs it through a constructor function and returns the resulting array. + +The constructor function should be a stand alone function named Events and should have the following keys: +* author +* categories +* summary +* img_url +* date +* title + +Then, write an `/events` route with a callback function called getCurrentEvents. + +Next, write a function named getCurrentEvents that takes in the request and response as parameters. This function should call the mapCurrentEvents function and send the result to the front-end. + +------------------------------------------------------------------------------------------------ */ + + +// Express sever here +const createServer = () => { + const express=require('express'); + const app=express(); + + // Routes go here + app.get('/events', getCurrentEvents); + + // Solution code here... + + var server = app.listen(3301, function () { + var port = server.address().port; + console.log('Example app listening at port', port); + }); + return server; +}; + +const currentEvents = { + news: [ + { + author: "go", + category: [ + "world" + ], + description: "Israel is bracing for more political turmoil with a midnight deadline looming on coalition talks between the country's two most powerful political parties...", + id: "1eff5f00-ce1e-4de0-922f-1b70299e9fe2", + image: "https://s.abcnews.com/images/International/WireAP_1a3a822a09ae4b7a98550a530cf88780_16x9_992.jpg", + language: "en", + published: "2020-04-13 18:00:33 +0000", + title: "Israel's coalition talks falter ahead of midnight deadline", + url: "https://abcnews.go.com/International/wireStory/israels-coalition-talks-falter-ahead-midnight-deadline-70122257" + }, + { + author: "@allahpundit", + category: [ + "politics" + ], + description: "Federalism....", + id: "2bede54d-9df8-4eda-8ea4-5fe166c6b13c", + image: "https://hotair.com/wp/wp-content/uploads/2020/04/n-6.jpg", + language: "en", + published: "2020-04-13 18:00:14 +0000", + title: "Cuomo: Some northeastern and mid-Atlantic states will be announcing a regional re-opening plan this afternoon", + url: "https://hotair.com/archives/allahpundit/2020/04/13/cuomo-northeastern-mid-atlantic-states-will-announcing-regional-re-opening-plan-afternoon/" + }, + { + author: "Authored by:\n \n Daniel Iglesias", + category: [ + "technology", + "gadgets" + ], + description: "We're back this week with more applications and games out this week. It's up to you to now take advantage and check them out....", + id: "8572f23a-06e4-4e55-afa0-33f0b43d00d3", + image: "https://fscl01.fonpit.de/userfiles/6727621/image/2nd_YEAR/Random/Play_store_ANDROIDPIT.jpg", + language: "en", + published: "2020-04-13 18:00:13 +0000", + title: "The best new apps and games launched for Easter | AndroidPIT", + url: "https://www.androidpit.com/apps-of-the-week-11-04-2020" + }, + { + author: "AndroidPIT", + category: [ + "technology", + "gadgets" + ], + description: "Our winners and losers of the week provide joy and disappointment. Disney+, Microsoft and many more have polarized this week in tech.(This is a preview - click here to read the entire entry.)...", + id: "671b1ea0-91a4-4f6b-aca3-0b81bec60bc3", + image: "None", + language: "en", + published: "2020-04-13 18:00:13 +0000", + title: "Winner and loser of the week: spring fever at Disney, long faces at Microsoft", + url: "https://www.androidpit.com/winner-loser-disney-microsoft" + }, + { + author: "wtae", + category: [ + "general" + ], + description: "Amazon plans to hire 75,000 more workers to meet increased demand for household essentials and other goods spurred by the coronavirus....", + id: "d341119d-2689-422e-ad43-9a5647dad69e", + image: "https://kubrick.htvapps.com/htv-prod-media.s3.amazonaws.com/images/lead-s098194910-300-1536076653960312366.jpg?crop=1.00xw:0.753xh;0,0.154xh&resize=640:*", + language: "en", + published: "2020-04-13 18:00:12 +0000", + title: "Amazon hiring 75,000 more workers to keep up with demand during coronavirus outbreak", + url: "https://www.wtae.com/article/amazon-hiring-75000-more-workers-to-keep-up-with-demand-during-coronavirus-outbreak/32129871" + }, + { + author: "wtae", + category: [ + "general" + ], + description: "If I can help out those who need it the most, I want to go ahead and do that....", + id: "7beda240-ce3a-458a-ad83-8ffca0f2512b", + image: "https://kubrick.htvapps.com/vidthumb/images/stitch-200413-grocery-delivery0-1586797913.jpg?crop=1xw:1xh;center,top&resize=640:*", + language: "en", + published: "2020-04-13 18:00:12 +0000", + title: "Teen starts website to deliver groceries to seniors during coronavirus outbreak", + url: "https://www.wtae.com/article/teen-starts-website-to-deliver-groceries-to-seniors-during-coronavirus-outbreak/32130620" + }, + { + author: "espn", + category: [ + "sports" + ], + description: "Kamara is heading into the final year of his contract, so he could push for a long-term deal. The question is: With his unique role, what is he worth?...", + id: "b3c211ff-30c8-45a0-9c0a-3895dd2b84a3", + image: "https://a2.espncdn.com/combiner/i?img=%2Fphoto%2F2019%2F1223%2Fr645131_1296x729_16%2D9.jpg", + language: "en", + published: "2020-04-13 18:00:10 +0000", + title: "Alvin Kamara looms as Saints' next big contract decision", + url: "https://www.espn.com/blog/new-orleans-saints/post/_/id/33054/alvin-kamara-looms-as-saints-next-big-contract-decision" + }, + { + author: "Mike Wehner", + category: [ + "science" + ], + description: "Air pollution on the East Coast of the United States has dropped by as much as 30% according to data from NASA satellites.\nA side-by-side comparison of air pollution levels from 2015-2019 and 2020 rev...", + id: "eb423ae0-a9c3-4d6e-af7d-c110953d4d63", + image: "None", + language: "en", + published: "2020-04-13 17:59:52 +0000", + title: "The coronavirus pandemic has cleaned up the air on the East Coast", + url: "https://bgr.com/2020/04/12/coronavirus-updates-air-pollution-quality-nasa/" + }, + { + author: "Mike Wehner", + category: [ + "science" + ], + description: "Science can't decide how effective surgical masks and homemade alternatives are at preventing the spread of coronavirus. \nThe CDC suggests making your own masks at home, but researchers can't say if t...", + id: "dfc77c05-7446-4a32-85ca-0b2cccd4c779", + image: "None", + language: "en", + published: "2020-04-13 17:59:52 +0000", + title: "Scientists still can't decide if face masks actually do anything", + url: "https://bgr.com/2020/04/13/coronavirus-mask-effectiveness-surgical-how-to/" + } + ] +} + +function getCurrentEvents(request, response){ + // Solution code here... + response.status(200).send(mapCurrentEvents()); + +} + + // Solution code here... + const mapCurrentEvents = () => currentEvents.news.map(value => new Event(value)); + + + +function Event(obj){ + // Solution code here... + this.author = obj.author; + this.categories = obj.category; + this.summary = obj.summary; + this.img_url = obj.img_url; + this.date = obj.date; + this.title = obj.title; +} + +/* ------------------------------------------------------------------------------------------------ +CHALLENGE 2 + +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. +------------------------------------------------------------------------------------------------ */ + +const countNumberOfElements = (arr) => { + // Solution code here... + const sum = arr.reduce((sumSoFar, value, index) => { + return sumSoFar = sumSoFar + 1; + }, 0); + return sum; + +}; + +/* ------------------------------------------------------------------------------------------------ +CHALLENGE 3 + +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 = (arr) => { + // Solution code here... + let answer = arr.reduce((characters, value, index) => { + characters.push(value.name); + return characters; + }, []); + return answer; +}; + +/* ------------------------------------------------------------------------------------------------ +CHALLENGE 4 + +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. +------------------------------------------------------------------------------------------------ */ + + // Solution code here... + const reversedString = (str) => str.split('').reduce((reverse, characters) => characters + reverse, ''); + + +/* ------------------------------------------------------------------------------------------------ +CHALLENGE 5 - Stretch Goal + +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 = (arr) => { + // Solution code here... + const newArr = arr.reduce((sumSoFar, profile) => { + if (profile.children) { + for (let child = 0; child < profile.children.length; child++) { + sumSoFar++; + } + } + return sumSoFar; + }, 0); + return newArr; +}; + +/* ------------------------------------------------------------------------------------------------ +CHALLENGE 6 - Stretch Goal + +Write a function that, given an array of numbers as input, uses reduce to calculate the array's average value. + +Hint: The accumulator should begin as { count: 0, sum: 0 } +------------------------------------------------------------------------------------------------ */ + +const calculateAverage = (arr) => { + // Solution code here... + let countAndSum = arr.reduce((accumulator, value) => { + accumulator.count = accumulator.count + 1; + accumulator.sum = accumulator.sum + value; + return accumulator; + }, { count: 0, sum: 0, }); + let average = countAndSum.sum / countAndSum.count; + return average; +}; + +/* ------------------------------------------------------------------------------------------------ +CHALLENGE 7 - Stretch Goal + +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 = (arr) => { + // Solution code here... + let count = arr.reduce((counter, value) => { + if (isPrime(value)) { + counter = counter + 1; + } + return counter; + }, 0); + return count; +}; + +/* ------------------------------------------------------------------------------------------------ +CHALLENGE 8 - Stretch Goal + +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, arr) => { + // Solution code here... +}; + +/* ------------------------------------------------------------------------------------------------ +CHALLENGE 9 - Stretch Goal + +Write a function named extractChildren that, given the array of characters from challenge 4, 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 = (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-09.test.js +------------------------------------------------------------------------------------------------ */ + +describe('Testing challenge 1', () => { + test('It should return an array of object instances with a key of author', () => { + expect(mapCurrentEvents()[0].author).toStrictEqual("go"); + }); + + test('It should return an array of object instances with a key of categories', () => { + expect(mapCurrentEvents()[0].categories).toStrictEqual(["world"]); + }); + const request = require('supertest'); + + let server; + + beforeEach(function () { + server = createServer(); + }); + + afterEach(function () { + server.close(); + }); + + test('responds to /events', function testSlash(done) { + request(server) + .get('/events') + .expect(200, done); + }); + + test('404 everything else', function testPath(done) { + request(server) + .get('/foo/bar') + .expect(404, done); + }); +}); + +describe('Testing challenge 2', () => { + test('It should return the length of the array', () => { + expect(countNumberOfElements([1, 2, 3, 4, 5])).toStrictEqual(5); + }); +}); + +describe('Testing challenge 3', () => { + test('It should return an array continaing the names of the characters', () => { + expect(returnNames(starWarsData)).toStrictEqual([ 'Luke Skywalker', 'C-3PO', 'R2-D2', 'Darth Vader', 'Leia Organa' ]); + expect(returnNames(starWarsData).length).toStrictEqual(5); + }); +}); + +describe('Testing challenge 4', () => { + test('It should return the string with the characters in reverse order', () => { + expect(reversedString('Code 301')).toStrictEqual('103 edoC'); + }); +}); + +describe('Testing challenge 5', () => { + test('It should return the total number of children', () => { + expect(countNumberOfChildren(characters)).toStrictEqual(14); + }); +}); + +describe('Testing challenge 6', () => { + 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 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); + }); +}); + +xdescribe('Testing challenge 8', () => { + 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 }); + }); +}); + +xdescribe('Testing challenge 9', () => { + 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); + }); +});