Skip to content

Instantly share code, notes, and snippets.

@peterschussheim
Last active September 13, 2016 20:46
Show Gist options
  • Save peterschussheim/f6a0af91683a6bb4735b145d0953484f to your computer and use it in GitHub Desktop.
Save peterschussheim/f6a0af91683a6bb4735b145d0953484f to your computer and use it in GitHub Desktop.
Chapter 4
function addEntry(squirrel) { ///This version reads its first argument (squirrel) in the normal way and then goes over the rest of the arguments (the loop starts at index 1, skipping the first) to gather them into an array.
var entry = {events: [], squirrel: squirrel};
for (var i = 1; i < arguments.length; i++) {
entry.events.push(arguments[i]);
}
journal.push(entry);
}
addEntry(true, "work", "touched tree", "pizza", "running", "television"); ///Need to import the journal object into cell.
var todoList = [];
function rememberTo(task) {
todoList.push(task);
}
function whatIsNext() {
return todoList.shift();
}
function urgentlyRememberTo(task) {
todoList.unshift(task);
}
var arr = [1, 2, 3, 2, 1];
arr.indexOf(2) ///Both `indexOf` and `lastIndexOf` take an optional second argument that indicates where to start searching from.
arr.lastIndexOf()
var arr2 = [0, 1, 2, 3, 4];
arr2.slice(2, 4) ///takes a start index and an end index and returns an array that has only the elements between those indices. The start index is inclusive, the end index exclusive.
arr2.slice(2) ///When the end index is not given, `slice` will take all of the elements after the start index. Strings also have a `slice` method, which has a similar effect.
function remove(array, index) {
return array.slice(0, index)
.concat(array.slice(index + 1));
}
remove(["a", "b", "c", "d", "e"], 2)
var day1 = {
squirrel: false,
events: ["work", "touched tree", "pizza", "running",
"television"]
};
var journal = [
{events: ["work", "touched tree", "pizza",
"running", "television"],
squirrel: false},
{events: ["work", "ice cream", "cauliflower",
"lasagna", "touched tree", "brushed teeth"],
squirrel: false},
{events: ["weekend", "cycling", "break",
"peanuts", "beer"],
squirrel: true},
/* and so on... */
];
var object1 = {value: 10};
object1.value = 15;
object1
var object2 = object1;
var object3 = {value: 10};
var journal = [];
function addEntry(events, didITurnIntoASquirrel) {
journal.push({
events: events,
squirrel: didITurnIntoASquirrel
});
}
addEntry(["work", "touched tree", "pizza", "running",
"television"], false);
addEntry(["work", "ice cream", "cauliflower", "lasagna",
"touched tree", "brushed teeth"], false);
addEntry(["weekend", "cycling", "break", "peanuts",
"beer"], true);
var JOURNAL = [
{"events":["carrot","exercise","weekend"],"squirrel":false},
{"events":["bread","pudding","brushed teeth","weekend","touched tree"],"squirrel":false},
{"events":["carrot","nachos","brushed teeth","cycling","weekend"],"squirrel":false},
{"events":["brussel sprouts","ice cream","brushed teeth","computer","weekend"],"squirrel":false},
{"events":["potatoes","candy","brushed teeth","exercise","weekend","dentist"],"squirrel":false},
{"events":["brussel sprouts","pudding","brushed teeth","running","weekend"],"squirrel":false},
{"events":["pizza","brushed teeth","computer","work","touched tree"],"squirrel":false},
{"events":["bread","beer","brushed teeth","cycling","work"],"squirrel":false},
{"events":["cauliflower","brushed teeth","work"],"squirrel":false},
{"events":["pizza","brushed teeth","cycling","work"],"squirrel":false},
{"events":["lasagna","nachos","brushed teeth","work"],"squirrel":false},
{"events":["brushed teeth","weekend","touched tree"],"squirrel":false},
{"events":["lettuce","brushed teeth","television","weekend"],"squirrel":false},
{"events":["spaghetti","brushed teeth","work"],"squirrel":false},
{"events":["brushed teeth","computer","work"],"squirrel":false},
{"events":["lettuce","nachos","brushed teeth","work"],"squirrel":false},
{"events":["carrot","brushed teeth","running","work"],"squirrel":false},
{"events":["brushed teeth","work"],"squirrel":false},
{"events":["cauliflower","reading","weekend"],"squirrel":false},
{"events":["bread","brushed teeth","weekend"],"squirrel":false},
{"events":["lasagna","brushed teeth","exercise","work"],"squirrel":false},
{"events":["spaghetti","brushed teeth","reading","work"],"squirrel":false},
{"events":["carrot","ice cream","brushed teeth","television","work"],"squirrel":false},
{"events":["spaghetti","nachos","work"],"squirrel":false},
{"events":["cauliflower","ice cream","brushed teeth","cycling","work"],"squirrel":false},
{"events":["spaghetti","peanuts","computer","weekend"],"squirrel":true},
{"events":["potatoes","ice cream","brushed teeth","computer","weekend"],"squirrel":false},
{"events":["potatoes","ice cream","brushed teeth","work"],"squirrel":false},
{"events":["peanuts","brushed teeth","running","work"],"squirrel":false},
{"events":["potatoes","exercise","work"],"squirrel":false},
{"events":["pizza","ice cream","computer","work"],"squirrel":false},
{"events":["lasagna","ice cream","work"],"squirrel":false},
{"events":["cauliflower","candy","reading","weekend"],"squirrel":false},
{"events":["lasagna","nachos","brushed teeth","running","weekend"],"squirrel":false},
{"events":["potatoes","brushed teeth","work"],"squirrel":false},
{"events":["carrot","work"],"squirrel":false},
{"events":["pizza","beer","work","dentist"],"squirrel":false},
{"events":["lasagna","pudding","cycling","work"],"squirrel":false},
{"events":["spaghetti","brushed teeth","reading","work"],"squirrel":false},
{"events":["spaghetti","pudding","television","weekend"],"squirrel":false},
{"events":["bread","brushed teeth","exercise","weekend"],"squirrel":false},
{"events":["lasagna","peanuts","work"],"squirrel":true},
{"events":["pizza","work"],"squirrel":false},
{"events":["potatoes","exercise","work"],"squirrel":false},
{"events":["brushed teeth","exercise","work"],"squirrel":false},
{"events":["spaghetti","brushed teeth","television","work"],"squirrel":false},
{"events":["pizza","cycling","weekend"],"squirrel":false},
{"events":["carrot","brushed teeth","weekend"],"squirrel":false},
{"events":["carrot","beer","brushed teeth","work"],"squirrel":false},
{"events":["pizza","peanuts","candy","work"],"squirrel":true},
{"events":["carrot","peanuts","brushed teeth","reading","work"],"squirrel":false},
{"events":["potatoes","peanuts","brushed teeth","work"],"squirrel":false},
{"events":["carrot","nachos","brushed teeth","exercise","work"],"squirrel":false},
{"events":["pizza","peanuts","brushed teeth","television","weekend"],"squirrel":false},
{"events":["lasagna","brushed teeth","cycling","weekend"],"squirrel":false},
{"events":["cauliflower","peanuts","brushed teeth","computer","work","touched tree"],"squirrel":false},
{"events":["lettuce","brushed teeth","television","work"],"squirrel":false},
{"events":["potatoes","brushed teeth","computer","work"],"squirrel":false},
{"events":["bread","candy","work"],"squirrel":false},
{"events":["potatoes","nachos","work"],"squirrel":false},
{"events":["carrot","pudding","brushed teeth","weekend"],"squirrel":false},
{"events":["carrot","brushed teeth","exercise","weekend","touched tree"],"squirrel":false},
{"events":["brussel sprouts","running","work"],"squirrel":false},
{"events":["brushed teeth","work"],"squirrel":false},
{"events":["lettuce","brushed teeth","running","work"],"squirrel":false},
{"events":["candy","brushed teeth","work"],"squirrel":false},
{"events":["brussel sprouts","brushed teeth","computer","work"],"squirrel":false},
{"events":["bread","brushed teeth","weekend"],"squirrel":false},
{"events":["cauliflower","brushed teeth","weekend"],"squirrel":false},
{"events":["spaghetti","candy","television","work","touched tree"],"squirrel":false},
{"events":["carrot","pudding","brushed teeth","work"],"squirrel":false},
{"events":["lettuce","brushed teeth","work"],"squirrel":false},
{"events":["carrot","ice cream","brushed teeth","cycling","work"],"squirrel":false},
{"events":["pizza","brushed teeth","work"],"squirrel":false},
{"events":["spaghetti","peanuts","exercise","weekend"],"squirrel":true},
{"events":["bread","beer","computer","weekend","touched tree"],"squirrel":false},
{"events":["brushed teeth","running","work"],"squirrel":false},
{"events":["lettuce","peanuts","brushed teeth","work","touched tree"],"squirrel":false},
{"events":["lasagna","brushed teeth","television","work"],"squirrel":false},
{"events":["cauliflower","brushed teeth","running","work"],"squirrel":false},
{"events":["carrot","brushed teeth","running","work"],"squirrel":false},
{"events":["carrot","reading","weekend"],"squirrel":false},
{"events":["carrot","peanuts","reading","weekend"],"squirrel":true},
{"events":["potatoes","brushed teeth","running","work"],"squirrel":false},
{"events":["lasagna","ice cream","work","touched tree"],"squirrel":false},
{"events":["cauliflower","peanuts","brushed teeth","cycling","work"],"squirrel":false},
{"events":["pizza","brushed teeth","running","work"],"squirrel":false},
{"events":["lettuce","brushed teeth","work"],"squirrel":false},
{"events":["bread","brushed teeth","television","weekend"],"squirrel":false},
{"events":["cauliflower","peanuts","brushed teeth","weekend"],"squirrel":false}
];
// This makes sure the data is exported in node.js —
// `require('./path/to/04_data.js')` will get you the array.
if (typeof module != "undefined" && module.exports)
module.exports = JOURNAL;
function phi(table) {
return (table[3] * table[0] - table[2] * table[1]) /
Math.sqrt((table[2] + table[3]) *
(table[0] + table[1]) *
(table[1] + table[3]) *
(table[0] + table[2]));
}
function hasEvent(event, entry) { /// To extract a two-by-two table for a specific event from this journal, we must loop over all the entries and tally up how many times the event occurs in relation to squirrel transformations.
return entry.events.indexOf(event) != -1;
}
function tableFor(event, journal) { ///The `hasEvent` function tests whether an entry contains a given event. Arrays have an `indexOf` method that tries to find a given value (in this case, the event name) in the array and returns the index at which it was found or -1 if it wasn’t found. So if the call to `indexOf` doesn’t return -1, then we know the event was found in the entry.
var table = [0, 0, 0, 0];
for (var i = 0; i < journal.length; i++) {
var entry = journal[i], index = 0;
if (hasEvent(event, entry)) index += 1;
if (entry.squirrel) index += 2;
table[index] += 1;
} ///The body of the loop in `tableFor` figures out which box in the table each journal entry falls into by checking whether the entry contains the specific event it’s interested in and whether the event happens alongside a squirrel incident. The loop then adds one to the number in the array that corresponds to this box on the table.
return table;
}
tableFor("pizza", JOURNAL);
// → [76, 9, 4, 1]
var map = {}; ///We can use the square bracket access notation to create and read the properties and can use the `in` operator to test whether a given property exists.
function storePhi(event, phi) {
map[event] = phi;
}
storePhi("pizza", 0.069); ///A map is a technique to go from values in one domain (in this case, event names) to corresponding values in another domain (in this case, coefficients).
storePhi("touched tree", -0.081);
console.log("pizza" in map);
console.log(map["touched tree"]);
for(var event in map) { ///Show all events that we have stored a coefficient for.
console.log("The correlation for '" + event + "' is " + map[event]);
}
function gatherCorrelations(journal) {
var phis = {};
for (var entry = 0; entry < journal.length; entry += 1) {
var events = journal[entry].events;
for (var i = 0; i < events.length; i += 1) {
var event = events[i];
if (!(event in phis)) {
phis[event] = phi(tableFor(event, journal));
}
}
}
return phis;
}
var correlations = gatherCorrelations(JOURNAL);
correlations.pizza;
for (var event in correlations) {
(event + ": " + correleations[event]);
}
// deepEqual :: (Object, Object) -> Boolean
function deepEqual(a, b) {
if (a === b) {
return true;
}
if (a == null || typeof a != "object" || b == null || typeof b != "object") {
return false;
}
var propsInA = 0;
var propsInB = 0;
for (var prop in a) {
propsInA += 1;
}
for (var prop in b) {
propsInB += 1;
if (!(prop in a) || !deepEqual(a[prop], b[prop])) {
return false;
}
}
return propsInA == propsInB;
}
var obj = {here: {is: "an"}, object: 2};
deepEqual(obj, obj);
deepEqual(obj, {here: 1, object: 2});
deepEqual(obj, {here: {is: "an"}, object: 2});
// range :: Number, Number -> [Number]
function range(start, end, step) {
var results = [];
for (var i = start; i <= end; i += step) {
results.push(i);
}
return results;
}
// sum :: [Number] -> Number
function sum(arr) {
var total = arr.reduce(function(prev, curr) {
return prev + curr;
});
return total;
}
range(1, 100, -1);
// → [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
//console.log(range(5, 2, -1));
// → [5, 4, 3, 2]
sum(range(1, 10));
// → 55
// arrayToList :: [Number] -> Object ///Write a function `arrayToList` that builds up a data structure like the previous one when given `[1, 2, 3]` as argument.
function arrayToList(array) {
var list = null;
for (var i = array.length - 1; i >= 0; i -= 1) {
list = {value: array[i], rest: list};
}
return list;
}
var arrayTest = [20, 10];
var newList = arrayToList(arrayTest);
// listToArray :: Object -> [Number] ///Write a function that takes a list and returns an array from the list.
function listToArray(list) {
var array = [];
for (var node = list; node; node = node.rest) {
array.push(node.value)
}
return array;
}
listToArray(newList)
// prepend :: Element, List -> List ///Takes an** element** and a **list** and creates a **new list** that adds the element to the **front of** the input list.
function prepend(value, list) {
return {value: value, rest: list};
}
prepend(10, prepend(20, null))
// nth :: [Number], Number -> Number ///Takes a list and a position (integer) and returns the element at the given position (pos) in the list, or `undefined` when there is no such element.
function nth(list, n) {
if (!list) {
return undefined;
} else if (n === 0) {
return list.value;
} else {
return nth(list.rest, n - 1);
}
}
var secondIdx = nth(newList, 2)
function reverseArray(array){
var reversedArr = [];
for (var i = array.length - 1; i >= 0; i -= 1) {
reversedArr.push(array[i]);
}
return reversedArr;
}
function reverseArrayInPlace(array) {
for (var i = 0; i < Math.floor(array.length / 2); i += 1) {
var old = array[i]; ///1. Briefly hold on to one of the elements.
array[i] = array[array.length - 1 - i]; ///2. Overwrite that one with its mirror image.
array[array.length - 1 - i] = old; ///3. Put the old value from the local variable in place where the mirror image used to be.
}
return array
}
console.log(reverseArray(["A", "B", "C"])); // → ["C", "B", "A"];
var arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue); // → [5, 4, 3, 2, 1]
"coconuts".slice(4, 7); ///Every string value has a number of methods. The most useful ones are probably `slice` and `indexOf`, which resemble the array methods of the same name.
"coconut".indexOf("u");
"one two three".indexOf("ne"); ///One difference of string's indexOf is that it can take a string containing more than one character, compared to the array method that looks only for a single element.
" okay \n ".trim();
var string = "abc";
string.length;
string.charAt(0);
string[1];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment