Last active
May 13, 2016 12:53
-
-
Save beaucharman/0a607ccc1b0f8b0e3771b7e75e6029fa to your computer and use it in GitHub Desktop.
Various exercises from eloquentjavascript.net
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Chapter two - exercise one | |
// c2e1(); | |
function c2e1() { | |
var hashCount = 1; | |
var hashes = '#'; | |
for (;hashCount <= 7; hashCount++) { | |
console.log(hashes); | |
hashes += '#'; | |
} | |
} | |
// Chapter two - exercise two | |
// c2e2(); | |
function c2e2() { | |
var n = 1; | |
var output; | |
for (;n <= 100; n++) { | |
output = getWord(n); | |
console.log(output); | |
} | |
function getWord(n) { | |
var word = ''; | |
if (n % 3 === 0) word += 'Fizz'; | |
if (n % 5 === 0) word += 'Buzz'; | |
return word || n; | |
} | |
} | |
// Chapter two - exercise three | |
// c2e3(); | |
function c2e3() { | |
var grid = 8; | |
var output = '\n'; | |
for (var i = 1; i <= grid; i++) { | |
if (i % 2 === 0) { | |
output += ' '; | |
} | |
for (var j = 1; j <= grid; j++) { | |
if (j % 2 === 0) { | |
output += ' '; | |
} else { | |
output += '#'; | |
} | |
} | |
output += '\n'; | |
} | |
console.log(output); | |
} | |
// Chapter three - exercise one | |
// c3e1(); | |
function c3e1() { | |
function min(a, b) { | |
if (a <= b) return a; | |
return b; | |
} | |
console.log(min(8, 6)); | |
} | |
// Chapter three - exercise two | |
// c3e2(); | |
function c3e2() { | |
function isEven(n) { | |
if(n === 0) { | |
return true; | |
} else if(n === 1) { | |
return false; | |
} else if(n < 0) { | |
return isEven(-n); | |
} else { | |
return isEven(n - 2) | |
} | |
} | |
console.log(isEven(3)); | |
console.log(isEven(86)); | |
console.log(isEven(-43)); | |
} | |
/** | |
* Chapter three - exercise three | |
*/ | |
c3e3(); | |
function c3e3() { | |
function countChars(haystack, needle) { | |
var wordLength = haystack.length; | |
var counter = 0; | |
for(var i = 0; i < wordLength; i++ ) { | |
if (haystack.charAt(i) === needle) { | |
counter++ | |
} | |
} | |
return counter; | |
} | |
function countBs(word) { | |
return countChars(word, 'B'); | |
} | |
console.log(countBs('hello there BiBi')); | |
console.log(countChars('All of the a\'s are here', 'a')); | |
} | |
/** | |
* Chapter four - exercise one | |
*/ | |
//c4e1(); | |
function c4e1() { | |
function flatten(arr) { | |
return arr.reduce(function(flatten, current) { | |
return flatten.concat(current); | |
}, []); | |
} | |
console.log(flatten([[1, 2], [4, 5]])); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment