Skip to content
This repository was archived by the owner on Sep 13, 2022. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 50 additions & 13 deletions chapter04.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,38 +8,75 @@


// Problem 1: The sum of a range
function range(start, end, step=1) {
// Your code here
function range(start, end, inc=1) {
var array = [];
if(start <= end){
for (var i=start; i<= end; i+= inc){
array.push(i);
}
}
else{
for(var x = start; x>= end; x-=inc){
array.push(x);
}
}
return array;
}

function sum(array) {
// Your code here
function sum(arr) {
var total = 0;
for(var i=0; i< arr.length; i++){
total += arr[i];
}
return total;
}

// Problem 2: Reversing an Array
function reverseArray(array) {
// Your code here
function reverseArray(arr) {
var new_arr = [];
for(var i = arr.length -1; i>= 0; i--){
new_arr.push(arr[i]);
}
return new_arr;
}

function reverseArrayInPlace(array) {
// Your code here
function reverseArrayInPlace(arr) {
for(var x = 0; x< Math.floor(arr.length/2);x++){
var tmp = arr[x];
arr[x] = arr[arr.length -1- x];
arr[arr.length-1-x] = tmp;
}
return arr;
}

// Problem 3: A List
function arrayToList(array) {
// Your code here
function arrayToList(arr) {
var list = null; // not [] bc it's not an array!!
for(var i = arr.length -1 ; i >= 0; i--){
list = {value: arr[i], rest: list}
}
return list;
}

function listToArray(list) {
// Your code here
arr = []; // we need this in order to create new array
for(var node= list; node; node = node.rest){
arr.push(node.value);
}
return arr;
}

function nth(list, position) {
// Your code here
for(var node = list; node; node = node.rest){
var tmp = listToArray(node);
}
return tmp[node];

}

function prepend(element, list) {
// Your code here
list = {value: element, rest: list};
return list;
}

// Problem 4: Deep comparison
Expand Down
15 changes: 12 additions & 3 deletions chapter05.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,24 @@ ancestry.forEach(function(person) {

// Problem 1: Flattening
function flatten(arrays) {
// Your code here
}
arr.reduce(function(curr, next){return curr.concat(next)});

// Problem 2: Mother-child age difference
/* This must return the average age difference instead of printing it */
var byName = {};
ancestry.forEach(function(person) {
byName[person.name] = person;
});

function hadKnownMother(person){
return person.mother in byName;
}

function averageMomChildAgeDiff() {
// Your code here
return person.born - byName[person.mother].born;
}


// Problem 3: Historical life expectancy
/* This must return the object/map with centuries as keys and average age
for the century as the value
Expand Down