Last active
April 25, 2021 20:55
-
-
Save eugeneglova/b6b17fa10aa1d376479c9470c207802c to your computer and use it in GitHub Desktop.
Fill array with missing values using recursion
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,3,8,9,17] -> [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 ] | |
// Using recursion | |
var dates = [1,3,8,9,17]; | |
function nextI (i) {return i+1;} | |
function getMissingElements(nextI, element, currentNextElement) { | |
var nextElement = nextI(element); | |
if (nextElement === currentNextElement) { | |
return []; | |
} | |
return [nextElement].concat(getMissingElements(nextI, nextElement, currentNextElement)); | |
} | |
dates.reduce(function(memo, element, index, arr) { | |
var currentNextElement = arr[nextI(index)]; | |
memo.push(element); | |
if (index + 1 !== arr.length) { | |
memo = memo.concat(getMissingElements(nextI, element, currentNextElement)); | |
} | |
return memo; | |
}, []); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment