Last active
August 23, 2017 20:37
-
-
Save AaronHarris/1258d3d0135617cb78fb365039dce5c9 to your computer and use it in GitHub Desktop.
Testing different possible implementations for lodash to add an intersperse method in https://github.com/lodash/lodash/issues/2339
This file contains hidden or 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
``` | |
_.intersperse(["a", "b", "c"], "+"); | |
// ["a", "+", "b", "+", "c"] | |
intersperse = function intersperse(arr, sep) { | |
var i = arr.length, | |
separr; | |
if (!i) return []; | |
if (i < 2) return arr.slice(); | |
i = i * 2 - 1; | |
separr = new Array(i); | |
while (i--) { | |
separr[i] = i % 2 === 0 ? arr[Math.floor(i / 2)] : sep; | |
} | |
return sep; | |
}; | |
``` | |
function intersperse(arr, obj) { | |
if (!arr.length) return []; | |
if (arr.length === 1) return arr.slice(0); | |
var items = [arr[0]]; | |
for (var i = 1, len = arr.length; i < len; ++i) { | |
items.push(obj, arr[i]); | |
} | |
return items; | |
} | |
/** | |
* Creates an array in which the contents of the given array are interspersed | |
* with... something. If that something is a function, it will be called on each | |
* insertion. | |
*/ | |
function intersperse(array, something) { | |
if (array.length < 2) { return array } | |
var result = [], i = 0, l = array.length | |
if (typeof something == 'function') { | |
for (; i < l; i ++) { | |
if (i !== 0) { result.push(something()) } | |
result.push(array[i]) | |
} | |
} | |
else { | |
for (; i < l; i ++) { | |
if (i !== 0) { result.push(something) } | |
result.push(array[i]) | |
} | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment