Last active
September 11, 2015 17:48
-
-
Save ceane/366fb0cf8bc2fdb6c5be to your computer and use it in GitHub Desktop.
Insert an item at a certain index in a recurring number of items inside of an array
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
/** | |
* Insert an item (d) at a certain index (b) in a | |
* recurring number (a) of items inside of an array (c) | |
* | |
* "For every 20 items in an array, | |
* insert this at the 12th index in that section" | |
* | |
* var myArray = Array.from({length: 80}, (v, k) => k); | |
* insertItemEvery(20, 12, myArray, "Hello index"); | |
* | |
* @param {number} a - Amount of items per section | |
* @param {number} b - Index to insert item at | |
* @param {array} c - Array to make inserts in | |
* @param {any} d - Item to insert | |
*/ | |
function insertItemEvery(a, b, c, d) { | |
var L = c.length; | |
var t = Math.floor(L / a) + (L % a >= b ? 1 : 0); | |
var T = Math.floor((L + t) / a) + ((L + t) % a >= b ? 1 : 0); | |
var C = []; | |
for (var i = 0, j = 0; i < T; i++) { | |
var e = i * a; | |
var f = e + b - (i + 1); | |
var g = e + a; | |
var D = Array.isArray(d) ? d[j++ % d.length] : d; | |
C = [...C, ...c.slice(e, f), D, ...c.slice(f, g)]; | |
} | |
var CL = C.length - T; | |
return CL < L ? C.concat(c.slice(CL, L)) : C; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment