JS Problems Flashcards
(11 cards)
Find the smallest integer in an array
class SmallestIntegerFinder { findSmallestInt(args) { return Math.min(...args) } } or const arr = [2, 3, 1]; console.log(Math.min(...arr));
Write a function that converts the input string to uppercase
function makeUpperCase(str) { return str.toUpperCase( ); } or const str = 'hello world'; console.log(str.toUppercase( ));
Build a function that returns an array of integers from n to 1 where n>0
const reverseSeq = n => { let arr = [ ]; for (let i=n; i>0, i--) { arr.push(i); } return arr; };
You are given the length and width of a 4-sided polygon. The polygon can either be a rectangle or a square. If it’s a square, return its area. If it’s a rectangle, return its perimeter.
const areaOrPerimeter = function(l, w) { return l === w ? l * w : (l + w) * 2; };
Create a function that answers the question “Are you playing banjo?” If your name starts with the letter “R” or lowercase “r”, you are playing banjo!
The function takes a name as its only argument, and returns one of the following strings:
name + “plays banjo”
name + “does not play banjo”
function areYouPlayingBanjo(name) { if (name[0] == 'R' || name[0] == 'r') return name + "plays banjo"; }else { return name + "does not play banjo"; } or function areYouPlayingBanjo(name) { if (name[0].toLowerCase( ) == 'r') { return name + 'plays banjo'; }else { return name + 'does not play banjo'; } }
The cockroach is one of the fastest insects. Write a function that takes its speed in km per hour and returns it in cm per second, rounded down to the integer (=floored).
function cockroachSpeed(s) { return Math.floor(s*100000/3600); } or function cockroachSpeed(s) { const secsInHour = 3600; const centimetersInKilometers = 100000; return Math.floor((s*centimetersInKilometers)/secsInHour); }
Given an array of integers as strings and numbers, return the sum of the array values as if all were numbers. Return your answer as a number.
function sumMix(x) { return x.map(a => +a).reduce((a, b) => a + b); }
Given a non-empty array of integers, return the result of multiplying the values together in order.
function grow(x) { return x.reduce((a, b) => a * b);
Write a program that finds the summation of every number from 1 to num. The number will always be a positive integer greater than 0.
var summation = function (num) { let result = 0; for (var i = i; i <= num; i++) { result += i; } return result; }
You get an array of numbers, return the sum of all the positive ones. If there is nothing to sum the sum default is 0.
function positiveSum(arr) { return arr.reduce((a, b) => a + (b > 0 ? b : 0), 0); }
Write a function called repeatStr which repeats the given string exactly n times.
function repeatStr (n, s) { return s.repeat(n); }