Prep Katas Flashcards
(23 cards)
Very simple, given a number, find its opposite.
function opposite(number) { //your code here }
//Additive Inverse ‘ - ‘
return -number;
Convert Boolean values to strings ‘Yes’ or ‘No’.
function boolToWord( bool ){ //your code here }
return bool? ‘Yes’:’No’;
Create a function that takes an integer as an argument and returns “Even” for even numbers or “Odd” for odd numbers.
function even_or_odd(number) { // ... }
//Modulus (remainder)
return number % 2 === 0 ? ‘Even : ‘Odd’ ;
Unfinished Loop - Bug Fixing #1
Oh no, Timmy’s created an infinite loop! Help Timmy find and fix the bug in his unfinished for loop!
function createArray(number){ var newArray = [];
for(var counter = 1; counter <= number; ){ newArray.push(counter); }
return newArray;
}
// sentry:variable that controls loop // Initialisation | Condition | Change
…
for(var counter = 1; counter <= number; counter ++ ){
newArray.push(counter);
}
…
Jenny has written a function that returns a greeting for a user. However, she’s in love with Johnny and would like to greet him slightly differently. She added a special case to her function, but she made a mistake.
function greet(name){ return "Hello, " + name + "!"; if(name === "Johnny") return "Hello, my love!"; }
//Exiting function too early. //Move return to the end of the function
if(name === “Johnny”) {
return “Hello, my love!”;
}
return “Hello, “ + name + “!”;
Give you a function animal, accept 1 parameter:obj like this:
{name:”dog”,legs:4,color:”white”}
And return a string like this:
“This white dog has 4 legs.”
function animal(obj){ return ? }
//String interpolation & Template Literals //Property Accessors.
return This ${obj.color} ${obj.name} has ${obj.legs} legs.
;
Write a function called repeatStr which repeats the given string string exactly n times.
function repeatStr (n, s) { return ''; }
//String.repeat(count);
return s.repeat(n);
// New variable, empty str //For loop n times: str+=s; //Return str;
//New variable, empty arr //For loop n time: str.push(s); //Return str.join('');
Complete the square sum function so that it squares each number passed into it and then sums the results together.
For example, for [1, 2, 2] it should return 9 because 1^2 + 2^2 + 2^2 = 9.
function squareSum(numbers){
}
// Array.reduce
return numbers.reduce((acc,num)=> acc + Math.pow(num,2),0);
//For loop let sumSquares = 0; for ( let i=0 ; i
Given a string, you have to return a string in which each character (case-sensitive) is repeated once.
function doubleChar(str) { // Your code here }
//arr.map
return str
.split(‘’)
.map(char=>char+char)
.join(‘’);
//for loop
let newStr =''; for ( let i=0; i
Consider an array/list of sheep where some sheep may be missing from their place. We need a function that counts the number of sheep present in the array (true means present).
function countSheeps(arrayOfSheep) { // TODO May the force be with you }
// arr.filter.length
return arrayOfSheep.filter(sheep=>sheep ===true).length;
Write a function findNeedle() that takes an array full of junk but containing one “needle”
After your function finds the needle it should return a message (as a string) that says:
“found the needle at position index”
function findNeedle(haystack) { // your code here }
// arr.indexOf(element)
let index = haystack.indexOf(‘needle’)
return index !== -1 ? found the needle at position ${index}
: ‘oops! no needle here’;
Simple, remove the spaces from the string, then return the resultant string.
function noSpace(x){
}
// str to arr and back to str
return x
.split(‘ ‘)
.join(‘’)
// str.replace
return x.replace(/\s/g,’’);
You take your son to the forest to see the monkeys. You know that there are a certain number there (n), but your son is too young to just appreciate the full number, he has to start counting them from 1.
As a good parent, you will sit and count with him. Given the number (n), populate an array with all numbers up to and including that number, but excluding zero.
function monkeyCount(n) { // your code here }
// For loop value of n
let countArr = []; for ( let i = 1 ; i <= n ; i++ ){ countArr.push(i); } return countArr;
Create a function with two arguments that will return an array of the first (n) multiples of (x).
Assume both the given number and the number of times to count will be positive numbers greater than 0.
Return the results as an array (or list in Python, Haskell or Elixir).
function countBy(x, n) { var z = [];
return z;
}
//for loop value of n
var z = []; for( let i = 1 ; i <= n ; i++ ){ z.push(x*i); } return z;
Write a function that takes an array of words and smashes them together into a sentence and returns the sentence. You can ignore any need to sanitize words or add punctuation, but you should add spaces between each word. Be careful, there shouldn’t be a space at the beginning or the end of the sentence!
[‘hello’, ‘world’, ‘this’, ‘is’, ‘great’] => ‘hello world this is great’
function smash (words) {
};
// arr.join
return words.join(‘ ‘)
Return the number (count) of vowels in the given string.
We will consider a, e, i, o, u as vowels for this Kata (but not y).
The input string will only consist of lower case letters and/or spaces.
function getCount(str) { var vowelsCount = 0;
// enter your majic here
return vowelsCount;
}
// str.match & ternary operator
let anyVowels = str.match(/[aeiou]/g);
return anyVowels ? anyVowels.length : 0;
Return the average of the given array rounded down to its nearest integer.
function getAverage(marks){ //TODO : calculate the downward rounded average of the marks array }
//arr.reduce to sum up //divided by marks.length // returned Math.floor(result)
return Math.floor(marks.reduce((acc,mark)=>acc+mark,0)/marks.length);
The function should take one parameter: an object/dict with two or more name-value pairs which represent the members of the group and the amount spent by each.
The function should return an object/dict with the same names, showing how much money the members should pay or receive.
function splitTheBill(x) { //code away...
}
// make arr of values // calculate avg per person: values reduce/length //for every person in x : update value to math.floor of initial value - avg. //return x
let values = Object.values(x); let owedPerPerson = values.reduce((acc,num)=> acc+num,0)/values.length; for (let person in x){ x[person]= Math.round((x[person]-owedPerPerson)*100)/100; } return x;
Replace all vowel to exclamation mark in the sentence. aeiouAEIOU is vowel.
function replace(s){ //coding and coding....
}
return s.replace(/[aeiou]/gi,’!’) ;
Every month, a random number of students take the driving test at Fast & Furious (F&F) Driving School. To pass the test, a student cannot accumulate more than 18 demerit points.
At the end of the month, F&F wants to calculate the average demerit points accumulated by ONLY the students who have passed, rounded to the nearest integer.
Write a function which would allow them to do so. If no students passed the test that month, return ‘No pass scores registered.’.
let filtered = list.filter(x=>x <=18); let avg=Math.round(filtered.reduce((acc,num)=>acc+num,0)/filtered.length) ; return filtered.length !== 0 ? avg : 'No pass scores registered.';
For example, if student X has a lesson for 1hr 20 minutes, he will be charged $40 (30+10) for 1 hr 30 mins and if he has a lesson for 5 minutes, he will be charged $30 for the full hour.
Out of the kindness of its heart, F&F also provides a 5 minutes grace period. So, if student X were to have a lesson for 65 minutes or 1 hr 35 mins, he will only have to pay for an hour or 1hr 30 minutes respectively.
For a given lesson time in minutes (min) , write a function price to calculate how much the lesson costs.
function cost (mins) { return; }
let total = 30;
if (mins > 65) { mins-=60; if (mins % 30 <= 5) { total += (Math.floor(mins / 30)) * 10 } else { total += ((Math.floor(mins / 30))+1) * 10 } }
return total;
Given two integers a and b, which can be positive or negative, find the sum of all the integers between and including them and return it. If the two numbers are equal return a or b.
Note: a and b are not ordered!
function getSum( a,b ) { //Good luck! }
//assign new variable to min and max //for loop to create new array with from min to max //reduce to sum array values
let minNum = Math.min(a, b); let maxNum = Math.max(a, b);
let sumArr = [];
for (let i = minNum; i <= maxNum; i++) { sumArr.push(i); }
return sumArr.reduce((acc, n) => acc + n, 0);
Complete the solution so that it returns the greatest sequence of five consecutive digits found within the number given. The number will be passed in as a string of only digits. It should return a five digit integer.
The number passed may be as large as 1000 digits.
1234567890 67890 is the greatest sequence of 5 consecutive digits.
function solution(digits){
}
//new variable empty arr to hold substrings //for loop to divide into substrings and push them to new variable. // parseInt() or number() to substrings into numbers //return math.max of new arr
let answer = [];
for (let i = digits.length - 5; i >= 0; i--) { let substring = parseInt(digits.substring(i, i + 5),10); answer.push(substring);
}
return Math.max(...answer);