diff --git a/index.js b/index.js index e69de29bb..95d51046c 100644 --- a/index.js +++ b/index.js @@ -0,0 +1,141 @@ +//Collection Functions (Arrays or Objects) + +const myEach = (collection, callback) => { + if (Array.isArray(collection)) { + for (let i = 0; i < collection.length; i++) { + callback(collection[i]) + } + } else { + for (let key in collection) { + callback(collection[key]) + } + } + return collection +} + +const myMap = (collection, callback) => { + const mapArray = [] + + myEach(collection, (item, index, collection) => { + mapArray.push(callback(item, index, collection)) + }) + + return mapArray +} + +const myReduce = (collection, callback, acc) => { + + const objectValues = [] + + if (!Array.isArray(collection)) { + for (let key in collection) { + objectValues.push(collection[key]) + } + collection = objectValues + } + + if (!acc) { + acc = collection[0] + + myEach(collection.slice(1), (value) => { + acc = callback(acc, value) + }) + return acc + } + myEach(collection, (value) => { + acc = callback(acc, value) + }) + + return acc + +} + +const myFind = (collection, predicate) => { + for (let i = 0; i < collection.length; i++) { + if (predicate(collection[i])) { + return collection[i]; + } + } + return undefined +} + +const myFilter = (collection, predicate) => { + const filteredArray = [] + + for (let i = 0; i < collection.length; i++) { + if (predicate(collection[i])) { + filteredArray.push(collection[i]) + } + } + + return filteredArray +} + +const mySize = collection => { + + const objectKeys = [] + + if (!Array.isArray(collection)) { + for (let key in collection) { + objectKeys.push(key) + } + collection = objectKeys + } + + return collection.length +} + + +//Array Functions + +const myFirst = (array, n) => { + if (n) { + return array.slice(0, n) + } + return array[0] +} + +const myLast = (array, n) => { + + if (n) { + return array.slice(-n) + } + return array[mySize(array)-1] +} + +const mySortBy = (array, callback) => { + return [...array].sort((a, b) => { + const valA = callback(a); + const valB = callback(b); + + if (typeof valA === 'string' && typeof valB === 'string') { + return valA.localeCompare(valB); + } + + return valA - valB; + }) +} + +const myFlatten = (array, [shallow], newArr=[]) => { + +} + +//Object Functions + +const myKeys = object => { + const keys = [] + + for (let key in object) { + keys.push(key) + } + return keys +} + +const myValues = function (object) { + const values = [] + + for (let key in object) { + values.push(object[key]) + } + return values +}