Skip to content

Instantly share code, notes, and snippets.

@Melipone
Created February 16, 2011 02:38
Show Gist options
  • Save Melipone/828758 to your computer and use it in GitHub Desktop.
Save Melipone/828758 to your computer and use it in GitHub Desktop.
Exercises in Chapter 6 of Eloquent Javascript
// coming soon
// Ex. 6.1
function forEach(array, action) {
for (var i = 0; i < array.length; i++)
action(array[i]);
}
function reduce(combine, base, array) {
forEach(array, function (element) {
base = combine(base, element);
});
return base;
}
function addIfZero (base, element) {
if (element == 0) {
return (base + 1);
}
else
return base;
}
//returns the number of zeroes in an array
function countZeros (array) {
return reduce (addIfZero, 0, array);
}
function filterFN (test) {
function addMe (base, element) {
if (test (element))
return base + 1;
else
return base;
}
return addMe;
}
function testIfZero (element) {
return (element === 0); // no type coercion
}
function countIf (testFN, array) {
var mycount = filterFN(testFN);
return reduce (mycount, 0, array);
}
var myarr = [0,1,3,0,0];
countIf(testIfZero, myarr);
// okay, looking at the solutions, countIf could have been abstracted further
// with a general equals function instead of just testing for 0
// Ex. 6.2
function isHeader (header) {
// check for % and return the number of %
for (var mychar in header) {
if (header.charAt(mychar) != "%")
return Number(mychar);
}
return 0;
}
function processParagraph (paragraph) {
// return an object with content: and type: properties
var mypar = {content: paragraph, type: "p"}; // initialize with default
var header = isHeader(paragraph);
if (header > 0) {
mypar.content = paragraph.slice(header);
mypar.type = "h"+header;
}
return mypar;
}
var paragraphs = recluseFile().split("\n\n");
print("Found ", paragraphs.length, " paragraphs.");
function map(func, array) {
var result = [];
forEach(array, function (element) {
result.push(func(element));
});
return result;
}
map (processParagraph, paragraphs);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment