Skip to content

Instantly share code, notes, and snippets.

@insin
Created March 1, 2014 23:50
Show Gist options
  • Save insin/9299529 to your computer and use it in GitHub Desktop.
Save insin/9299529 to your computer and use it in GitHub Desktop.
/**
* 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
}
@neopunisher
Copy link

if (!Array.prototype.intersperse) {
  Object.defineProperty(Array.prototype, 'intersperse', {
    value: function(something) {
      if (this === null) {
        throw new TypeError( 'Array.prototype.intersperse ' + 
          'called on null or undefined' );
      }
      var isFunc = (typeof something == 'function')
      
      return this.concat.apply([], 
        this.map(function(e,i) { 
          return i ? [isFunc ? something(this[i-1]) : something, e] : [e] }.bind(this)))
    }
  });
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment