Problem solutions Flashcards
Solutions to codewars and other js problems
Write a program that creates a string that represents an 8×8 grid, using newline characters to separate lines. At each position of the grid there is either a space or a “#” character. The characters should form a chessboard.
let size = 8; let board = ""; for (let y = 0; y < size; y++) { for (let x = 0; x < size; x++) { if ((x + y) % 2 == 0) { board += " "; } else { board += "#"; } } board += "\n"; } console.log(board);
Make a function that will return a greeting statement that uses an input; your program should return, “Hello, <name> how are you doing today?".</name>
function greet(name){ return `Hello, ${name} how are you doing today?` }
Return the middle character of a word. If word length is odd, return the middle character. If even, return the middle 2 characters
function getMiddle(s) { return s.substr(Math.ceil(s.length / 2 - 1), s.length % 2 === 0 ? 2 : 1); }
Create a function that takes an integer as an argument and returns “Even” for even numbers or “Odd” for odd numbers
function evenOrOdd(number) { return number % 2 === 0 ? 'Even' : 'Odd'; }
You get an array of numbers, return the sum of all of the positives ones. If there is nothing to sum, the sum is default to 0.
Example [1,-4,7,12] => 1 + 7 + 12 = 20
function positiveSum(arr) { return arr.filter(num => num > 0).reduce((total, curr) => total += curr, 0) }
You are given an odd-length array of integers, in which all of them are the same, except for one single number.
Complete the method which accepts such an array, and returns that single different number.
The input array will always be valid! (odd-length >= 3)
function stray(numbers) { let arr = numbers.sort(); if (arr[0] !== arr[1]) { return arr[0]; } else { return arr[arr.length - 1]; } }
Write a solution to cleanup arrays. Accepts an input array of values and returns a new array with all empty strings, 0, null and undefined removed.
function squeakyClean(arr) { return arr.filter(Boolean); }
An isogram is a word that has no repeating letters, consecutive or non-consecutive. Implement a function that determines whether a string that contains only letters is an isogram. Assume the empty string is an isogram. Ignore letter case.
function isIsogram(str) { return str.length != new Set(str.toLowerCase()).size; }
Square every digit of a number and concatenate them.
E.g. if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1. (81-1-1-81)
function squareDigits(num) { let numArr = num.toString().split(''); let newArr = numArr.map((num) => num * num); return Number(newArr.join('')); }