Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Write a function called getSum that takes in two numbers and returns the sum of those two numbers
- function getSum(num1, num2) {
- return num1 + num2
- //write function
- }
- // console.log(getSum(1, 2)) // 3
- // getSum(10, 5) // 15
- // getSum(2, 2) // 4
- // getSum(10, 5) // 15
- //=================================================
- // Write a function called calculator that takes in 2 numbers and an operator and returns the result of the calculation.
- function calculator(num1, num2, operator) {
- // let result
- // switch (operator) {
- // case '+':
- // result = num1 + num2
- // break
- // case '-':
- // result = num1 - num2
- // break
- // case '*':
- // result = num1 * num2
- // break
- // case '/':
- // result = num1 / num2
- // break
- // default:
- // throw new Error('Not a valid Operator')
- // }
- if (operator === '+') {
- return num1 + num2
- }
- if (operator === '-') return num1 - num2
- if (operator === '*') return num1 * num2
- if (operator === '/') return num1 / num2
- throw new Error('Not a valid Operator')
- // return result
- }
- console.log(calculator(1, 2, '*')) // 3
- // calculator(10, 5, '-') // 5
- // calculator(2, 2, '*') // 4
- // calculator(10, 5, '/') // 2
- //=================================================
- // Write a function called countOccurrences that takes in a string and a character and returns the number of occurrences of that character in the string.
- // Lowercase and uppercase characters are considered different characters
- function countOccurrences(str, char) {
- //write code here
- let count = 0
- for (let letter of str) {
- letter === char && count++
- }
- return count
- }
- console.log(countOccurrences('hello', 'l')) //2
- // countOccurrences('hello', 'z') // 0
- // You may assume that each word consists of only letters and spaces
- function titleCase(str) {
- //write code here
- //make all sentence lowecase
- // const lowecaseStr = str.toLowerCase()
- // console.log(lowecaseStr)
- // //devide by space (split)
- // const splitStr = lowecaseStr.split(' ')
- // console.log(splitStr)
- // //make each array elements first letter to uppercase
- // for (let i = 0; i < splitStr.length; i++) {
- // splitStr[i] = splitStr[i][0].toUpperCase() + splitStr[i].slice(1)
- // }
- // console.log(splitStr)
- // return splitStr.join(' ')
- return str.replace(/\b\w/g, (match) => match.toUpperCase())
- }
- console.log(titleCase("I'm a little tea pot")) // I'm A Little Tea Pot
- // titleCase('sHoRt AnD sToUt'); // Short And Stout
- // titleCase('HERE IS MY HANDLE HERE IS MY SPOUT'); // Here Is My Handle Here Is My Spout
- //=================================================
- // Write a function called removeDuplicates that takes in an array and returns a new array with duplicates removed.
- // function removeDuplicates(arr) {
- // const resultSet = new Set(arr)
- // console.log(Array.from(resultSet))
- // return Array.from(resultSet)
- // const resultArr = []
- // for (let num of arr) {
- // if (!resultArr.includes(num)) {
- // resultArr.push(num)
- // }
- // }
- // console.log(resultArr)
- // }
- // removeDuplicates([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
- // removeDuplicates([1, 1, 1, 1, 1, 1, 1, 1, 1, 1]) // [1]
- // removeDuplicates([1, 2, 3, 4, 5, true, 1, 'hello' 2, 3, 'hello', true]); // [1, 2, 3, 4, 5, true, 'hello']
- //=================================================
- // Write a function called arrayIntersection that takes in two arrays and returns an array containing the intersection of the two input arrays (i.e., the common elements that appear in both arrays).
- function arrayIntersection(arr1, arr2) {
- // const resultArr = []
- // for (let num of arr1) {
- // console.log(num)
- // if (arr2.includes(num)) {
- // resultArr.push(num)
- // }
- // }
- // console.log(Array.from(new Set(resultArr)))
- const set1 = new Set(arr1)
- const intersectionArr = []
- for (let num of arr2) {
- console.log(num)
- if (set1.has(num)) {
- intersectionArr.push(num)
- }
- }
- return intersectionArr
- }
- console.log(arrayIntersection([1, 2, 3, 3, 4, 5], [1, 3, 5, 7, 9])) // should return [1, 3, 5]
- // arrayIntersection([1, 1, 1, 1, 1], [2, 2, 2, 2, 2]); // should return []
- // arrayIntersection([1, 2, 3, 4, 5], [5, 4, 3, 2, 1]); // should return [1, 2, 3, 4, 5]
- //=================================================
- // Write a function called displayLikes that takes in an array of names and returns a string of who likes the post.
- // The function should return a string formatted as follows:
- // If no one likes it, it should return 'no one likes this'
- // If one person likes it, it should return '{name} likes this'
- // If two people like it, it should return '{name1} and {name2} like this'
- // If three people like it, it should return '{name1}, {name2} and {name3} like this'
- // If more than three people like it, it should return '{name1}, {name2} and {x} others like this'
- function displayLikes(namesArr) {
- // Get the length of the array
- const length = namesArr.length
- // Return the appropriate string based on the length of the array
- if (length === 0) {
- return 'no one likes this'
- } else if (length === 1) {
- return `${namesArr[0]} likes this`
- } else if (length === 2) {
- return `${namesArr[0]} and ${namesArr[1]} like this`
- } else if (length === 3) {
- return `${namesArr[0]}, ${namesArr[1]} and ${namesArr[2]} like this`
- } else {
- return `${namesArr[0]}, ${namesArr[1]} and ${length - 2} others like this`
- }
- }
- // displayLikes([]) // 'no one likes this'
- // displayLikes(['Peter']) // 'Peter likes this'
- // displayLikes(['Jacob', 'Alex']) // 'Jacob and Alex like this'
- // displayLikes(['Max', 'John', 'Mark']) // 'Max, John and Mark like this'
- console.log(displayLikes(['Alex', 'Jacob', 'Mark', 'Max'])) // 'Alex, Jacob and 2 others like this'
- // displayLikes(['Alex', 'Jacob', 'Mark', 'Max', 'Jill']) // 'Alex, Jacob and 3 others like this'
- //=================================================
- // Write a function called findMissingNumber that takes in an array of unique numbers from 1 to n (inclusive), where one number is missing. It should return the missing number.
- // If an empty array is passed in, it should return 1
- // If nothing is passed in, it should return undefined
- function findMissingNumber(arr) {
- //write code here
- if (!arr || !Array.isArray(arr)) return undefined
- if (arr.length === 0) return 1
- const n = arr.length + 1
- const expectedSum = (n * (n + 1)) / 2
- console.log(expectedSum)
- // let total = 0
- // for(let num of arr){
- // total += num
- // }
- // console.log(total)
- const totalSum = arr.reduce((total, num) => total + num, 0)
- console.log(expectedSum - totalSum)
- return expectedSum - totalSum
- //(n * (n +1)) / 2
- }
- console.log(findMissingNumber([1, 2, 3, 4, 6, 7, 8, 9, 10])) // 5
- // findMissingNumber([10, 8, 6, 7, 5, 4, 2, 3, 1]); // 9
- // findMissingNumber([10, 5, 1, 2, 4, 6, 8, 3, 9]); // 7
- //=================================================
- // Write a function called findMissingLetter that takes in an array of consecutive (increasing) letters as input and returns the missing letter in the array.
- function findMissingLetter(arr) {
- const alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
- const startIndex = alphabet.indexOf(arr[0])
- for (let i = 0; i < arr.length; i++) {
- if (arr[i] !== alphabet[startIndex + i]) {
- return alphabet[startIndex + i]
- }
- }
- //write code here
- }
- console.log(findMissingLetter(['a', 'b', 'c', 'd', 'f'])) // => "e"
- // findMissingLetter(['O', 'Q', 'R', 'S']); // => "P"
- // findMissingLetter(['t', 'u', 'v', 'w', 'x', 'z']); // => "y"
- //=================================================
- // Write a function called validateEmail that takes in a string and returns whether the string is a valid email address. For the purposes of this challenge, a valid email address is defined as a string that contains an @ symbol and a . symbol.
- function validateEmail(email) {
- // const emailRegex = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/
- // return emailRegex.test(email)
- // Check if the email contains the "@" symbol
- // if (email.indexOf('@') === -1) {
- // return false
- // }
- // // Split the email into the local part and domain
- // const [localPart, domain] = email.split('@')
- // // Check if the local part and domain meet the minimum length requirements
- // if (localPart.length === 0 || domain.length < 3) {
- // return false
- // }
- // // Check if the domain extension consists of at least two characters
- // const domainExtension = domain.split('.')
- // if (domainExtension.length < 2 || domainExtension[1].length < 2) {
- // return false
- // }
- // // If all checks pass, return true
- // return true
- //write code here
- }
- console.log(validateEmail('john@gmail.com')) // true
- validateEmail('john@gmail') // false
- //=================================================
- // Write a function called diceGameSimulation that simulates this dice game. The function should take one argument:
- // numSimulations: The number of times to simulate the dice game.
- // The game rules are if a 7 or 11 are rolled, the player wins and they get a result of win. If a 2, 3 or 12 are rolled they lose and get a result of lose. Anything else and they get a result of roll again.
- // The function should return an array of objects, where each object represents a simulation result. Each object should contain the following properties:
- // dice1: The value of the first dice (a random number between 1 and 6).
- // dice2: The value of the second dice (a random number between 1 and 6).
- // sum: The sum of the two dice values.
- // result: The result of the roll, which can be "win", "lose", or "roll again".
- function rollDice() {
- return Math.floor(Math.random() * 6 + 1)
- }
- function diceGameSimulation(numOfTry) {
- const results = []
- //write code here
- for (let i = 0; i < numOfTry; i++) {
- const dice1 = rollDice()
- const dice2 = rollDice()
- const sum = dice1 + dice2
- let result = ''
- if (sum === 7 || sum === 11) {
- result = 'win'
- } else if (sum === 2 || sum === 3 || sum === 12) {
- result = 'lose'
- } else {
- result = 'Roll Again'
- }
- results.push({ dice1, dice2, sum, result })
- }
- console.log(results)
- }
- diceGameSimulation(10)
- /*
- { dice1: 1, dice2: 5, sum: 6, result: 'roll again' },
- { dice1: 5, dice2: 6, sum: 11, result: 'win' },
- { dice1: 1, dice2: 1, sum: 2, result: 'lose' }
- */
- // Write a function called formatPhoneNumber that takes in an array of numbers and returns a string representing the phone number formed by concatenating the numbers in the specified format.
- //=================================================
- function formatPhoneNumber(numbers) {
- //write code here
- // Get the first 3 numbers and join them together
- const areaCode = numbers.slice(0, 3).join('')
- // Get the next 3 numbers and join them together
- const prefix = numbers.slice(3, 6).join('')
- // Get the last 4 numbers and join them together
- const lineNumber = numbers.slice(6).join('')
- console.log(`(${areaCode}) ${prefix}-${lineNumber}`)
- return `(${areaCode}) ${prefix}-${lineNumber}`
- }
- formatPhoneNumber([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]); // => "(123) 456-7890"
- // formatPhoneNumber([5, 1, 9, 5, 5, 5, 4, 4, 6, 8]); // => "(519) 555-4468"
- // formatPhoneNumber([3, 4, 5, 5, 0, 1, 2, 5, 2, 7]); // => "(345) 501-2527"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement