Skip to content

Instantly share code, notes, and snippets.

@victoralvarez84
Created August 27, 2015 13:46
Show Gist options
  • Save victoralvarez84/0e64584805678d1646b5 to your computer and use it in GitHub Desktop.
Save victoralvarez84/0e64584805678d1646b5 to your computer and use it in GitHub Desktop.
/* Part 1
*
* Define a function reverse() that computes
* the reversal of a string. For example,
* reverse("skoob") should return the
* string "books".
*/
function reverse(str){
var x = '';
for (var i = str.length; i > 0; i--)
x += str[i];
return x;
}
console.assert(reverse("books") === "skoob");
console.assert(reverse("we don't want no trouble") === "elbuort on tnaw t'nod ew");
/**
* Part 2
*
* Write a function findLongestWord() that takes an
* string returns the first, longest word in the array.
*
* i.e. findLongestWord("book dogs") should return "book"
*/
function findLongestWord(sentence){
var str = sentence.split(" ");
var longest = 0;
var word = null;
str.forEach(function(str) {
if (longest < str.length) {
longest = str.length;
word = str;
}
return word;
}
console.assert(findLongestWord("book dogs") === "book")
console.assert(findLongestWord("don't mess with Florida") === "Florida")
/**
* Part 3
*
* Write a function that calculates the sum of all the numbers in an array
*/
function sumOfArray(arr){
var sum = 0; //placeholder//
for(i = 0; i < arr.length; i ++) { //for loop to go through each variable in array//
sum += arr[i]; //sum is sum + array
}
return sum;
}
console.assert(sumOfArray([1, 2]) === 3);
console.assert(sumOfArray([]) === 0);
console.assert(sumOfArray([1, 2, 3]) === 6);
console.assert(sumOfArray([10, 9, 8]) === 27);
/**
* Part 4
*
* Write a function that takes two numbers as
* arguments and computes the sum of those two numbers.
*/
function sum(a, b){
return a + b;
}
console.assert(sum(8, 11) === 19);
console.assert(sum(4, 100) === 104);
/**
* Part 5
*
* write a function that finds the Greatest Common Denominator of two numbers
* - if no GCD exists, return 1
*/
function GCD(a, b){
if (b == 0) return a;
else return (GCD (b, a % b));
}
//euclid's alog, punched into javascript. Remember this for the future.//
console.assert(GCD(5,1) === 1);
console.assert(GCD(15,3) === 3);
console.assert(GCD(15,5) === 5);
console.assert(GCD(50,20) === 10);
/**
* Part 6
*
* write a function that prints out the Least Common Multiple of two numbers
*/
function LCM(a, b){
return (Math.abs(a * b) / GCD (a, b));
//euclid's algo, using absolute value function//
}
console.assert(LCM(10,10) === 10)
console.assert(LCM(2,5) === 10)
console.assert(LCM(3,6) === 6)
console.assert(LCM(0,1) === 1)
@victoralvarez84
Copy link
Author

Test

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment