Skip to content

Instantly share code, notes, and snippets.

@eugeneglova
Last active April 25, 2021 20:55
Show Gist options
  • Save eugeneglova/b6b17fa10aa1d376479c9470c207802c to your computer and use it in GitHub Desktop.
Save eugeneglova/b6b17fa10aa1d376479c9470c207802c to your computer and use it in GitHub Desktop.
Fill array with missing values using recursion
// [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