Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rlynjb/4daa009d9b65421608f9 to your computer and use it in GitHub Desktop.
Save rlynjb/4daa009d9b65421608f9 to your computer and use it in GitHub Desktop.
Basic Algorithm Scripting

Basic Algorithm Scripting

FreeCodeCamp - Bonfire series

My FreeCodeCamp profile [http://freecodecamp.com/rlynjb]


  1. [Bonfire: Reverse a String] (#file-reverse-a-string-js)
  2. [Bonfire: Factorialize a Number] (#file-factorialize-a-number-js)
  3. [Bonfire: Check for Palindromes] (#file-check-for-palindromes-js)
  4. [Bonfire: Find the Longest Word in a String] (#file-find-the-longest-word-in-a-string-js)
  5. [Bonfire: Title Case a Sentence] (#file-title-case-a-sentence-js)
  6. [Bonfire: Return Largest Numbers in Arrays] (#file-return-largest-numbers-in-arrays-js)
  7. [Bonfire: Confirm the Ending] (#file-confirm-the-ending-js)
  8. [Bonfire: Repeat a string repeat a string] (#file-repeat-a-string-repeat-a-string-js)
  9. [Bonfire: Truncate a string] (#file-truncate-a-string-js)
  10. [Bonfire: Chunky Monkey] (#file-chunky-monkey-js)
  11. [Bonfire: Slasher Flick] (#file-slasher-flick-js)
  12. [Bonfire: Mutations] (#file-mutations-js)
  13. [Bonfire: Falsy Bouncer] (#file-falsy-bouncer-js)
  14. [Bonfire: Seek and Destroy] (#file-seek-and-destroy-js)
  15. [Bonfire: Where do I belong] (#file-where-do-i-belong-js)
/*
Return true if the given string is a palindrome. Otherwise, return false.
A palindrome is a word or sentence that's spelled the same way both forward and backward, ignoring punctuation, case, and spacing.
You'll need to remove punctuation and turn everything lower case in order to check for palindromes.
We'll pass strings with varying formats, such as "racecar", "RaceCar", and "race CAR" among others.
Here are some helpful links:
String.replace()
String.toLowerCase()
*/
function palindrome(str) {
var origStr = str
.replace(/,/g,"")
.replace(/\./g,"")
.replace(/ /g,"")
.toLowerCase();
var reverseStr = str
.replace(/,/g,"")
.replace(/\./g,"")
.replace(/ /g,"")
.toLowerCase()
.split("").reverse().join("");
console.log(origStr + reverseStr);
if (origStr == reverseStr) {
return true;
} else {
return false;
}
}
palindrome("A man, a plan, a canal. Panama");
/*
Write a function that splits an array (first argument) into groups the length of size (second argument) and returns them as a multidimensional array.
Here are some helpful links:
Array.push()
*/
function chunk(arr, size) {
var f = [];
while (arr.length > 0) {
f.push(arr.splice(0, size));
}
//console.log(f);
// Break it up.
return f;
}
chunk(['a', 'b', 'c', 'd'], 2);
/*
Check if a string (first argument) ends with the given target string (second argument).
Here are some helpful links:
String.substr()
*/
function end(str, target) {
var s = str.split(' ');
var lastWord = s[s.length - 1];
var lastChar = str.substr(str.lastIndexOf());
console.log(target.length);
if (target.length == 1) {
return lastChar == target;
} else {
return lastWord == target;
}
}
end('Bastian', 'n');
/*
Return the factorial of the provided integer.
If the integer is represented with the letter n, a factorial is the product of all positive integers less than or equal to n.
Factorials are often represented with the shorthand notation n!
For example: 5! = 1 * 2 * 3 * 4 * 5 = 120
Here are some helpful links:
Arithmetic Operators
*/
function factorialize(num) {
var f = 1;
for(var i=1; i<=num; i++) {
f *= i;
}
return f;
}
factorialize(5);
/*
Remove all falsy values from an array.
Falsy values in javascript are false, null, 0, "", undefined, and NaN.
Here are some helpful links:
Boolean Objects
Array.filter()
*/
function bouncer(arr) {
// Don't show a false ID to this bouncer.
return arr.filter(Boolean);
}
bouncer([7, 'ate', '', false, 9]);
/*
Return the length of the longest word in the provided sentence.
Your response should be a number.
Here are some helpful links:
String.split()
String.length
*/
function findLongestWord(str) {
var s = str.split(' ');
var l = 0;
var w = null;
for (var i=0; i<s.length; i++) {
console.log(s[i].length);
if (l < s[i].length) {
l = s[i].length;
w = s[i];
}
}
return w.length;
}
findLongestWord('The quick brown fox jumped over the lazy dog');
/*
Return true if the string in the first element of the array contains all of the letters of the string in the second element of the array.
For example, ["hello", "Hello"], should return true because all of the letters in the second string are present in the first, ignoring case.
The arguments ["hello", "hey"] should return false because the string "hello" does not contain a "y".
Lastly, ["Alien", "line"], should return true because all of the letters in "line" are present in "Alien".
Here are some helpful links:
Array.indexOf()
*/
function mutation(arr) {
var s1 = arr[0].split('');
var s2 = arr[1].split('');
var a = 0;
var ind = [];
// get keys from s1 that match from s2
for (var i=0; i<s2.length; i++) {
a = s1.indexOf(s2[i]);
//console.log(a);
//if (a) {
ind.push(a);
//return true;
//}
}
console.log(ind);
console.log(s1);
//console.log(s1.length-1);
//console.log(a < s1.length-1 || a > s1.length-1);
return a != -1;
}
mutation(['zyxwvutsrqponmlkjihgfedcba', 'qrstu']);
/*
Repeat a given string (first argument) n times (second argument). Return an empty string if n is a negative number.
Here are some helpful links:
Global String Object
*/
function repeat(str, num) {
if (num < 0) {
return '';
} else {
return str.repeat(num);
}
}
repeat('abc', 3);
/*
Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays.
Remember, you can iterate through an array with a simple for loop, and access each member with array syntax arr[i] .
If you are writing your own Chai.js tests, be sure to use a deep equal statement instead of an equal statement when comparing arrays.
Here are some helpful links:
Comparison Operators
*/
function largestOfFour(arr) {
var h = [];
for (var i=0; i<arr.length; i++) {
h.push(Math.max.apply(Math, arr[i]));
//console.log(Math.max.apply(Math, arr[i]));
}
//console.log(h);
// You can do this!
return h;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
/*
Reverse the provided string.
You may need to turn the string into an array before you can reverse it.
Your result must be a string.
Here are some helpful links:
Global String Object
String.split()
Array.reverse()
Array.join()
*/
function reverseString(str) {
var reverseStr = str.split("").reverse().join("");
return reverseStr;
}
reverseString('hello');
/*
You will be provided with an initial array (the first argument in the destroyer function), followed by one or more arguments. Remove all elements from the initial array that are of the same value as these arguments.
Here are some helpful links:
Arguments object
Array.filter()
*/
function destroyer(arrayToRemoveStuffFrom) {
// arrayToRemoveStuffFrom should be the same as arguments[0]
// because it’s the first argument
var thingsToRemove = [];
for (var i = 1; i < arguments.length; i++) {
thingsToRemove.push(arguments[i]);
}
var result = arrayToRemoveStuffFrom.filter(function(value) {
// IF value IS IN thingsToRemove
// THEN return false
// ELSE return true
if (thingsToRemove.indexOf(value) >= 0) {
return false;
} else {
return true;
}
});
return result;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
/*
Return the remaining elements of an array after chopping off n elements from the head.
The head meaning the beginning of the array, or the zeroth index
Here are some helpful links:
Array.slice()
Array.splice()
*/
function slasher(arr, howMany) {
//console.log(arr.splice(howMany));
// it doesn't always pay to be first
return arr.splice(howMany);
}
slasher([1, 2, 3], 2);
/*
Return the provided string with the first letter of each word capitalized. Make sure the rest of the word is in lower case.
For the purpose of this exercise, you should also capitalize connecting words like "the" and "of".
Here are some helpful links:
String.charAt()
*/
function titleCase(str) {
var g = str.replace(/(\'\w|\w)+/g, function(t) {
return t.charAt(0).toUpperCase() + t.substr(1).toLowerCase();
//console.log(t.charAt(0).toUpperCase() + t.substr(1));
});
return g;
}
titleCase("I'm a little tea pot");
/*
Truncate a string (first argument) if it is longer than the given maximum string length (second argument). Return the truncated string with a "..." ending.
Note that the three dots at the end add to the string length.
If the length of the string is less than or equal to 3 characters, then the length of the three dots is not added to the string length.
Here are some helpful links:
String.slice()
*/
function truncate(str, num) {
if (str.length > num) {
return str.slice(0, num - 3) + '...';
} else {
return str.slice(0, num);
}
// Clear out that junk in your trunk
}
truncate('A-tisket a-tasket A green and yellow basket', 11);
/*
Return the lowest index at which a value (second argument) should be inserted into a sorted array (first argument).
For example, where([1,2,3,4], 1.5) should return 1 because it is greater than 1 (0th index), but less than 2 (1st index).
Here are some helpful links:
Array.sort()
*/
function where(arr, num) {
var newArr = arr.concat(num);
newArr.sort(function(a, b) {
return a - b;
});
var matchVal = newArr.indexOf(num);
// Find my place in this sorted array.
return matchVal;
}
where([40, 60], 50, "");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment