Skip to content

Instantly share code, notes, and snippets.

@davidejones
Last active March 21, 2018 15:41
Show Gist options
  • Save davidejones/222ba4ed0cf387dd220c178467c430fc to your computer and use it in GitHub Desktop.
Save davidejones/222ba4ed0cf387dd220c178467c430fc to your computer and use it in GitHub Desktop.
eloquentjavascript : chapter 4
const range = (start, end, step=1) => {
const data = [];
for(let i=start; i <= end; i=i+step) {
data.push(i);
}
return data;
};
console.log(range(3,6));
console.log(range(1,100,10));
const sum = (numbers) => {
return numbers.reduce((reduced, item) => reduced += item);
};
console.log(sum([1,2,3]));
console.log(sum(range(1, 10)));
const reverseArray = (data) => {
return data.map((item, i) => data[data.length-(i+1)]);
};
let data = [1,2,3];
console.log(reverseArray(data));
// check we didn't mutate original data
console.log(data);
// tried to do something a little different and iterate over half the array so its faster
// and modify the head and tail of array as we loop
const reverseArrayInPlace = (data) => {
for(let i=0; i < data.length/2; i++) {
const newStartNum = data.slice(data.length-(i+1), data.length-(i+1)+1)[0];
const newEndNum = data.slice(i, i+1)[0];
data[i] = newStartNum;
data[data.length-(i+1)] = newEndNum;
}
return data;
};
let data = [1,2,3,4,5,6];
console.log(reverseArrayInPlace(data));
// check we mutated original data
console.log(data);
function arrayToList(data) {
if (!data.length) return null;
const first = data.slice(0, 1)[0];
const remaining = data.slice(1, data.length);
return {value: first, rest:arrayToList(remaining) };
};
console.log(arrayToList([10, 20]));
function listToArray(obj, data = []) {
data.push(obj.value);
if(obj.rest) data = listToArray(obj.rest, data);
return data;
};
console.log(listToArray(arrayToList([10, 20, 30])));
const prepend = (el, list) => {
};
console.log(prepend(10, prepend(20, null)));
const nth = (list, num) => {
};
console.log(nth(arrayToList([10, 20, 30]), 1));
// range
[3,4,5,6]
// range with step
[1,11,21,31,41,51,61,71,81,91]
// sum
6
// sum range
55
// reverse array
[3,2,1]
[1,2,3] // <!-- original input data didn't get modified yay
// reverse array inplace
[6,5,4,3,2,1]
[6,5,4,3,2,1] // <!-- original input was modified yay
// array to list
{"value":10,"rest":{"value":20,"rest":null}}
// list to array
[10,20,30]
// prepend
// nth
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment