Skip to content

Instantly share code, notes, and snippets.

@TechNinjaWeb
Created April 7, 2015 00:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TechNinjaWeb/cc5443e43de8d3560413 to your computer and use it in GitHub Desktop.
Save TechNinjaWeb/cc5443e43de8d3560413 to your computer and use it in GitHub Desktop.
Eloquent Javascript Exercises
/*
Minimum
The previous chapter introduced the standard function Math.min that returns
its smallest argument. We can do that ourselves now. Write a function min
that takes two arguments and returns their minimum.
Recursion
We’ve seen that % (the remainder operator) can be used to test whether a
number is even or odd by using % 2 to check whether it’s divisible by two.
Here’s another way to define whether a positive whole number is even
or odd:
• Zero is even.
• One is odd.
• For any other number N, its evenness is the same as N − 2.
Define a recursive function isEven corresponding to this description.
The function should accept a number parameter and return a Boolean.
Test it on 50 and 75. See how it behaves on −1. Why? Can you think
of a way to fix this?
Bean Counting
You can get the N th character, or letter, from a string by writing "string"
.charAt(N), similar to how you get its length with "s".length. The returned
value will be a string containing only one character (for example, "b"). The
first character has position zero, which causes the last one to be found at position
string.length - 1. In other words, a two-character string has length 2,
and its characters have positions 0 and 1.
Write a function countBs that takes a string as its only argument and returns
a number that indicates how many uppercase “B” characters are in the
string.
Next, write a function called countChar that behaves like countBs, except
it takes a second argument that indicates the character that is to be counted
(rather than counting only uppercase “B” characters). Rewrite countBs to
make use of this new function.
*/
// Basic Min Function
(function min(a, b) {
if (a > b) return a;
if (b > a) return b;
})(5, 6)
// Recursion Function
(function isEven(num){
parseInt(num);
if (num % 2 == 0) return num + " is Even";
if (num % 2 == 1) return num + " is Odd";
if (num % 2 != 0 && num % 2 != 1) { num = 1; return isEven(num); };
if (num <= 0 || !!isNaN(num)) return isEven(num * -1);
})("fourteen")
// Bean Counting
(function beanCounter(string){
var stLen = string.length;
var count = 0;
for (var i=0;i<stLen;i++) { if (string.charAt(i) == "B") count++; }
return count;
})("Bravo Bear")
(function countChar(string, countThisChar){
var stLen = string.length;
var count = 0;
for (var i=0;i<stLen;i++) { if (string.charAt(i) == countThisChar) count++; }
return count;
})("Bravo Bear")
(function range(start, end) {
var arr = [];
var step = arguments[2] || 1;
if (arguments[2] && arguments[2] < 0) { for(var i=end;i>=start;i += step) { arr.push(i); }; }
else { for(var i=start;i<=end;i += step) { arr.push(i); }; }
return arr;
})(1,5,2)
(function sum(arr){
var sum = 0;
for (var i=0;i<arr.length;i++) {
sum += arr[i];
}
return sum;
})([1,5,7,5,7,4,3,6,8])
console.log(sum(range(1, 10)));
(function reverseArray(arr) {
var newArray = [];
arr.forEach(function(e, i){
newArray.unshift(e);
})
return newArray;
})([1,5,7,5,7,4,3,6,8])
// UNFINISHED --> FUNCTION IS TO
// RETURN SORTED ARRAY THAT IS
// PERMANENTLY REARRANGED
(function reverseArrayInPlace(arr) {
var newArray = [];
arr.forEach(function(e, i){
newArray.unshift(e);
})
arr.shift(0,-1);
return arr;
})([1,5,7,5,7,4,3,6,8])
/*
Write a function arrayToList that builds up a data structure like
the previous one when given[1, 2, 3] as argument, and write a listToArray
function that produces an array from a list.Also write the helper functions
prepend, which takes an element and a list and creates a new list that adds
the element to the front of the input list, and nth, which takes a list and
a number and returns the element at the given position in the list, or
undefined when there is no such element.
// CODE OUTPUT SAMPLE //
console.log(arrayToList([10, 20]));
→ {value: 10, rest: {value: 20, rest: null}}
console.log(listToArray(arrayToList([10, 20, 30])));
→ [10, 20, 30]
console.log(prepend(10, prepend(20, null)));
→ {value: 10, rest: {value: 20, rest: null}}
console.log(nth(arrayToList([10, 20, 30]), 1));
→ 20
*/
(function(){
var arr = [1, 2, 3];
function arrayToList(a) {
// builds up a data structure like
// the previous one when given
return {
value: a[0],
rest: (function (ar) {
return !!a[1] ? arrayToList(a.slice(1)) : null
})(a.slice(0))
};
}
function listToArray(o) {
// produces an array from a list
var a = (function _listToArray(obj){
var _a = [
obj.value,
!!obj.rest ? _listToArray(obj.rest) : null
];
return _a.concat.apply([], _a);
})(o)
a.length = a.length -1;
return a;
}
function prepend(e, o) {
// creates a new list that adds
// the element to the front of the input list
!o ? o = {value: e} : o;
var a = listToArray(o);
a.unshift(e);
return arrayToList(a);
}
function nth(list, pos) {
// takes a list and a number and returns the
// element at the given position in the list
return listToArray(list)[pos];
}
})()
/*
Write a function, deepEqual, that takes two values and returns true only
if they are the same value or are objects with the same properties
whose values are also equal when compared with a recursive call to deepEqual.
// CODE SAMPLE //
var obj = {here: {is: "an"}, object: 2};
console.log(deepEqual(obj, obj));
// → true
console.log(deepEqual(obj, {here: 1, object: 2}));
// → false
console.log(deepEqual(obj, {here: {is: "an"}, object: 2}));
// → true
*/
function deepEqual(a, b) {
return (function _deepEqual(_a, _b) {
if (typeof _a === 'object' && typeof _b === 'object')
for (prop in _a)
return !!_b.hasOwnProperty(prop) ? deepEqual(_a[prop], _b[prop]) : false
else
return _a === _b ? true : false
})(a, b)
}
// SECOND ATTEMPT AFTER CHAPTER 4
(function(gridSize, charset){
var grid = gridSize || 8,
chars = charset || ["X", "Y"],
chessBoard = {};
chessBoard.isEven = function(num) {
return num % 2 == 0;
}
chessBoard.buildRow = function(len, chars, pos) {
var res = '';
if (chessBoard.isEven(pos)) {
if (len == 0 || len == 1) return chars[0];
if (len > 1) { for (var i = 0;i<len;i++) { res += chessBoard.isEven(i) ? chars[0] : chars[1]; } }
return res;
} else {
if (len == 0 || len == 1) return chars[1];
if (len > 1) { for (var i = 0;i<len;i++) { res += chessBoard.isEven(i) ? chars[1] : chars[0]; } }
return res;
}
}
chessBoard.printGrid = function() {
var board = '';
for (var i=0;i<grid;i++){
board += chessBoard.buildRow(grid,chars,i) +"\n";
}
// Debug To Console for Preview
// console.log(board);
return board;
}
// Init Program
return chessBoard.printGrid();
})(8, ["#", " "])
/*
Write a program that creates a string that represents an 8×8 grid, using newline
characters to separate lines. At each position of the grid there is either a
space or a “#” character. The characters should form a chess board.
Passing this string to console.log should show something like this:
*/
(function createGrid(x, y, ex, wy) {
var oddLayer = [], evenLayer = [];
this.coords = [x, y];
this.charX = ex;
this.charY = wy;
// console.warn("Args in", x, y, ex, wy)
// console.warn("Ex", this.charX, "Wy", this.charY, "X", this.coords[0], "Y", this.coords[1])
for (i = 0; i < this.coords[0]; i++) {
if (this.coords[0] % 2 == 0) {
// console.warn("Iteration: " + i)
if ((i + 1) % 2 == 0) {
// console.log("Pushing Even Layer");
evenLayer.push(this.charX);
evenLayer.push(this.charY);
} else {
// console.log("Pushing Odd Layer");
oddLayer.push(this.charY);
oddLayer.push(this.charX);
}
} else if (this.coords[0] == 1) {
// console.warn("Building 1 x 1 Grid");
// console.log("Pushing One Layer");
oddLayer.push(this.charX);
} else {
// console.warn("Grid Is Not Square. Please Select Equal X & Y values.")
}
}
for (k = 0; k < this.coords[0] / 2; k++) {
if (k + 1 % 2 == 0) {
logToConsole(evenLayer.toString(), oddLayer.toString());
} else if (k + 1 % 2 != 0) {
logToConsole(oddLayer.toString(), evenLayer.toString());
} else {
logToConsole(oddLayer);
}
}
function logToConsole(eL, oL) {
if (!eL) console.log(oL);
if (!oL) console.log(eL);
if (eL && oL) {
console.log(eL);
console.log(oL);
}
}
})(1, 1, 'X', 'Y')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment