Created
January 8, 2020 22:41
-
-
Save BrentonCozby/c8ec68529ff30a9530c9c07f1d350582 to your computer and use it in GitHub Desktop.
arrayDepth function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 1 - (a) Reimplement Array.prototype.forEach as a standalone function that accepts an array and a callback | |
// (b) Invoke the function such that it logs the array's values individually on each line | |
// (c) Invoke the function such that it logs the array's indices individually on each line | |
const numberArrayOne = [1, 2, 3, 4, 5] | |
function forEach(list, cb) { | |
for (let i = 0; i < list.length; i++) { | |
cb(list[i], i, list) | |
} | |
} | |
// forEach(numberArrayOne, (number, index, list) => { | |
// console.log(number) | |
// }) | |
// 2 - (a) Reimplement Array.prototype.map as a standalone function that accepts an array and a callback | |
// (b) Invoke the function such that it returns an arraay with each value incremendted by 2. | |
// (c) Invoke the function such that it returns an arraay with each index incremendted by 1. | |
function map(list, cb) { | |
const newList = []; | |
for (let i = 0; i < list.length; i++) { | |
newList.push(cb(list[i], i, list)) | |
} | |
return newList | |
} | |
const newList = map(numberArrayOne, (number, index, list) => { | |
return number + 2 | |
}) | |
// console.log(newList) | |
const newListTwo = map(numberArrayOne, (number, index, list) => { | |
return index + 1 | |
}) | |
// console.log(newListTwo) | |
// 3 - Write a function 'arrayDepth' that given an array of arbitrarily nested arrays, return n, where n is the deepest level that contains a non-array value. | |
function arrayDepth(list, depth = 0) { | |
// Base Case(s): return depth | |
if (!Array.isArray(list)) { | |
return depth | |
} | |
if (list.length === 0) { | |
return 0; | |
} | |
// Recursive: | |
const depthList = list.map(item => { | |
return arrayDepth(item, depth + 1) | |
}) | |
return Math.max(...depthList) | |
} | |
const arr0 = [50] // => 1 | |
const arr1 = [10, 20, 30, 40 ] // => 1 | |
const arr2 = [[5], [[]]] // => 2 | |
const arr3 = [[10, 20 ], [[30, [40]]]] // => 4 | |
const arr4 = [] // => 0 | |
const arr5 = [[[]]] // => 0 | |
console.log("Depth 1: ", arrayDepth(arr0)) | |
console.log("Depth 1: ", arrayDepth(arr1)) | |
console.log("Depth 2: ", arrayDepth(arr2)) | |
console.log("Depth 4: ", arrayDepth(arr3)) | |
console.log("Depth 0: ", arrayDepth(arr4)) | |
console.log("Depth 0: ", arrayDepth(arr5)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment