From 069961efb8d30ae3226f6e8bd421572598d67a9c Mon Sep 17 00:00:00 2001 From: Lisa Cee Date: Fri, 17 Nov 2017 16:04:57 -0800 Subject: [PATCH] arrays +13 --- src/arrays.js | 33 +++++++++++++++++++++++++++++++++ src/es6.js | 2 ++ 2 files changed, 35 insertions(+) diff --git a/src/arrays.js b/src/arrays.js index b995952..bc2166a 100644 --- a/src/arrays.js +++ b/src/arrays.js @@ -8,34 +8,67 @@ const each = (elements, cb) => { // Iterates over a list of elements, yielding each in turn to the `cb` function. // This only needs to work with arrays. // based off http://underscorejs.org/#each + for (let x = 0; x < elements.length; x++) { + cb(elements[x], x); + } }; const map = (elements, cb) => { // Produces a new array of values by mapping each value in list through a transformation function (iteratee). // Return the new array. + const newArray = []; + for (let x = 0; x < elements.length; x++) { + newArray.push(cb(elements[x])); + } + return newArray; }; const reduce = (elements, cb, memo = elements.shift()) => { // Combine all elements into a single value going from left to right. // Elements will be passed one by one into `cb`. // `memo` is the starting value. If `memo` is undefined then make `elements[0]` the initial value. + for (let x = 0; x < elements.length; x++) { + if (memo === undefined) { + memo = elements[0]; + } + memo += elements[x]; + cb(memo); + } + return memo; }; const find = (elements, cb) => { // Look through each value in `elements` and pass each element to `cb`. // If `cb` returns `true` then return that element. // Return `undefined` if no elements pass the truth test. + for (let i = 0; i < elements.length; i++) { + const x = cb(elements[i]); + if (x === true) { + return elements[i]; + } + } + return undefined; }; const filter = (elements, cb) => { // Similar to `find` but you will return an array of all elements that passed the truth test // Return an empty array if no elements pass the truth test + const array = []; + for (let i = 0; i < elements.length; i++) { + if (cb(array[i]) === true) { + array.push(array[i]); + } + } + return array; }; /* Extra Credit */ const flatten = (elements) => { // Flattens a nested array (the nesting can be to any depth). // Example: flatten([1, [2], [3, [[4]]]]); => [1, 2, 3, 4]; + const newArray = []; + + return newArray; }; /* eslint-enable no-unused-vars, max-len */ diff --git a/src/es6.js b/src/es6.js index eb846ab..5761d3f 100644 --- a/src/es6.js +++ b/src/es6.js @@ -9,6 +9,8 @@ var food = 'pineapple'; + + var isMyFavoriteFood = function(food) { food = food || 'thousand-year-old egg'; //This sets a default value if `food` is falsey return food === 'thousand-year-old egg';