Skip to content

Instantly share code, notes, and snippets.

@amfischer
Created Feb 10, 2017
Embed
What would you like to do?
Algorithm Challenges
// #1
String.prototype.repeatify = function(num) {
var repeated_str = '';
for (var i = 0; i < num; i++) {
repeated_str = repeated_str + this;
}
return repeated_str;
}
'matt'.repeatify(3);
// #2
function isPrime(num) {
var counter = 2;
while(counter < num) {
if (num % counter === 0){
return false;
}
counter++;
}
return true;
}
isPrime(135);
// #3
function removeSpaces(str) {
str = str.trim();
if (str.indexOf(' ') !== -1) {
str = str.replace(' ', ' ');
removeSpaces(str);
} else {
console.log(str);
}
}
removeSpaces(' This is my name Bob. ');
// #4
function isPalindrome(str) {
var str2 = str.split('').reverse().join('');
return str === str2 ? true : false;
}
function isPalindrome(str) {
while (str.length > 0) {
if (str[0] === str[str.length - 1]) {
str = str.slice(1, str.length -1);
} else {
return false;
}
}
return true;
}
isPalindrome('madam'); // true
isPalindrome('cookies'); // false
// #6
function randomNum(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
randomNum(5, 9);
/*
#1 Write a function that repeats a string x number of times
'matt'.repeatify(3); // “mattmattmatt”
#2 Write a function that tests if a number is prime
isPrime(137); // true
isPrime(252); // false
#3 Remove extra spaces from this string, using a recursive strategy:
“ Hello, my name is Bob. “
#4 Create a Palindrome function (word is same if reversed)
isPalindrome('madam'); // true
isPalindrome('cookies'); // false
#5 Create a random number between any two variables:
randomNums(5, 9); // 6.3, 5.2, 8.9…
#6 Create a ‘slug’ from any Given title:
"Hello My Name is Bob" → hello-my-name-is-bob
"Why do you like slugs!!!" → why-do-you-like-slugs
createSlug(“Hello My Name is Bob”);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment