Skip to content
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
51 changes: 51 additions & 0 deletions src/arrays.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,22 @@ const each = (elements, cb) => {
// This only needs to work with arrays.
// You should also pass the index into `cb` as the second argument
// based off http://underscorejs.org/#each
for (let i = 0; i < elements.length; i++) {
cb(elements[i], i);
}
};

const map = (elements, cb) => {
// Do NOT use .map, to complete this function.
// Produces a new array of values by mapping each value in list through a transformation function (iteratee).
// Return the new array.
let mappedArray = [];

elements.forEach((el) => {
return mappedArray = [...mappedArray, cb(el)];

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Avoiding mutations here instead of using push.

});

return mappedArray;
};

const reduce = (elements, cb, startingValue) => {
Expand All @@ -28,26 +38,67 @@ const reduce = (elements, cb, startingValue) => {
// Elements will be passed one by one into `cb` along with the `startingValue`.
// `startingValue` should be the first argument passed to `cb` and the array element should be the second argument.
// `startingValue` is the starting value. If `startingValue` is undefined then make `elements[0]` the initial value.
let reducedValue = startingValue || elements[0];

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alternative way: let memo = startingValue || elementsCopy.shift();

const startingIndex = (startingValue !== undefined) ? 0 : 1;

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure how the solution gets away from determining the startingIndex.


for (let i = startingIndex; i < elements.length; i++) {
reducedValue = cb(reducedValue, elements[i]);
}

return reducedValue;
};

const find = (elements, cb) => {
// Do NOT use .includes, to complete this function.
// 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 element = elements[i];

if (cb(element)) {
return element;
}
}

return false;
};

const filter = (elements, cb) => {
// Do NOT use .filter, to complete this function.
// 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
let filteredElements = [];

for (let i = 0; i < elements.length; i++) {
const element = elements[i];

if (cb(element)) {
filteredElements = [...filteredElements, element];
}
}

return filteredElements;
};

/* STRETCH PROBLEM */

const flatten = (elements) => {
// Flattens a nested array (the nesting can be to any depth).
// Example: flatten([1, [2], [3, [[4]]]]); => [1, 2, 3, 4];
let flattenedElements = [];

for (let i = 0; i < elements.length; i++) {

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Prefer to use reduce here:

const flattenedArr = reduce(elements, (memo, item) => {
  if (Array.isArray(item)) return memo.concat(flatten(item));
  return memo.concat(item);
}, []);'
return flattenedArr;
);

const element = elements[i];

if (Array.isArray(element)) {
flattenedElements = flatten([...flattenedElements, element[0]]);
} else {
flattenedElements = [...flattenedElements, element];
}
}

return flattenedElements;
};

/* eslint-enable no-unused-vars, max-len */
Expand Down
11 changes: 11 additions & 0 deletions src/callbacks.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,35 @@
const firstItem = (arr, cb) => {
// firstItem passes the first item of the given array to the callback function.
cb(arr[0]);
};

const getLength = (arr, cb) => {
// getLength passes the length of the array into the callback.
cb(arr.length);
};

const last = (arr, cb) => {
// last passes the last item of the array into the callback.
cb(arr[arr.length - 1]);
};

const sumNums = (x, y, cb) => {
// sumNums adds two numbers (x, y) and passes the result to the callback.
const sum = x + y;
cb(sum);
};

const multiplyNums = (x, y, cb) => {
// multiplyNums multiplies two numbers and passes the result to the callback.
const product = x * y;
cb(product);
};

const contains = (item, list, cb) => {
// contains checks if an item is present inside of the given array/list.
// Pass true to the callback if it is, otherwise pass false.
const itemPresent = list.includes(item);
cb(itemPresent);
};

/* STRETCH PROBLEM */
Expand All @@ -29,6 +38,8 @@ const removeDuplicates = (array, cb) => {
// removeDuplicates removes all duplicate values from the given array.
// Pass the duplicate free array to the callback function.
// Do not mutate the original array.
const uniqueElements = new Set(array);
cb(Array.from(uniqueElements));
};

/* eslint-enable */
Expand Down
45 changes: 45 additions & 0 deletions src/closure.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,46 @@ const counter = () => {
// Example: const newCounter = counter();
// newCounter(); // 1
// newCounter(); // 2
let count = 0;

function incrementCount() {

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can also create an anonymous function and return it directly instead of declaring the function and separately returning it.

return count += 1;
}

return incrementCount;
};

const counterFactory = () => {
// Return an object that has two methods called `increment` and `decrement`.
// `increment` should increment a counter variable in closure scope and return it.
// `decrement` should decrement the counter variable and return it.

let count = 0;

const increment = () => count += 1;
const decrement = () => count -= 1;

return {

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Return a single object:

let count = 0;
return {
   increment: () => (++count),
   decrement: () => (--count),
};

increment,
decrement,
};
};

const limitFunctionCallCount = (cb, n) => {
// Should return a function that invokes `cb`.
// The returned function should only allow `cb` to be invoked `n` times.
let count = 0;

const invokeCb = (...options) => {
if (count < n) {
count += 1;

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use count++.

return cb(...options);
}

return null;
};

return invokeCb;
};

/* STRETCH PROBLEM */
Expand All @@ -27,6 +56,22 @@ const cacheFunction = (cb) => {
// If the returned function is invoked with arguments that it has already seen
// then it should return the cached result and not invoke `cb` again.
// `cb` should only ever be invoked once for a given set of arguments.

const cache = {};

const invokeCb = (...options) => {
const argument = options[0];

if (Object.prototype.hasOwnProperty.call(cache, argument)) {
return cache[argument];
}

const result = cb(argument);
cache[argument] = result;
return result;
};

return invokeCb;
};

/* eslint-enable no-unused-vars */
Expand Down
41 changes: 40 additions & 1 deletion src/objects.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,36 +5,75 @@ const keys = (obj) => {
// Retrieve all the names of the object's properties.
// Return the keys as strings in an array.
// Based on http://underscorejs.org/#keys
return Object.keys(obj);
};

const values = (obj) => {
// Return all of the values of the object's own properties.
// Ignore functions
// http://underscorejs.org/#values
return Object.values(obj);
};

const mapObject = (obj, cb) => {
// Like map for arrays, but for objects. Transform the value of each property in turn.
// http://underscorejs.org/#mapObject
const objectKeys = Object.keys(obj);

for (let i = 0; i < objectKeys.length; i++) {

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use forEach.

const key = objectKeys[i];
obj[key] = cb(obj[key]);
}

return obj;
};

const pairs = (obj) => {
// Convert an object into a list of [key, value] pairs.
// http://underscorejs.org/#pairs
const objectKeys = Object.keys(obj);
let keyValuePairs = [];

for (let i = 0; i < objectKeys.length; i++) {
const key = objectKeys[i];
keyValuePairs = [...keyValuePairs, [key, obj[key]]];
}

return keyValuePairs;
};

/* STRETCH PROBLEMS */

const invert = (obj) => {
// Returns a copy of the object where the keys have become the values and the values the keys.
// Assume that all of the object's values will be unique and string serializable.
// http://underscorejs.org/#invert
const objectKeys = Object.keys(obj);
let invertedObject = {};

for (let i = 0; i < objectKeys.length; i++) {

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use forEach.

const key = objectKeys[i];
const value = obj[key];
invertedObject[value] = key;
}

return invertedObject;
};

const defaults = (obj, defaultProps) => {
// Fill in undefined properties that match properties on the `defaultProps` parameter object.
// Return `obj`.
// http://underscorejs.org/#defaults
const defaultKeys = Object.keys(defaultProps);

for (let i = 0; i < defaultKeys.length; i++) {
const defaultKey = defaultKeys[i];

if (!obj.hasOwnProperty(defaultKey)) {
obj[defaultKey] = defaultProps[defaultKey];
}
}

return obj;
};

/* eslint-enable no-unused-vars */
Expand Down
1 change: 1 addition & 0 deletions tests/arrays.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ describe('arrays', () => {
const arr = [1, 2, 3, 4, 5];
const results = arrayMethods.flatten(arr);
expect(Array.isArray(results)).toBe(true);
expect(results).toEqual([1, 2, 3, 4, 5]);
});
it('should return a flattened array when given a nested array', () => {
const arr = [1, 2, 3, 4, 5, [6], [7]];
Expand Down