Skip to content

Instantly share code, notes, and snippets.

@aldonline
Created October 13, 2013 07:16
Show Gist options
  • Save aldonline/6959067 to your computer and use it in GitHub Desktop.
Save aldonline/6959067 to your computer and use it in GitHub Desktop.
polymorphic map() over Google Apps Script iterators and Arrays.
function _map( coll, f ){
var res = []
var isIterator = ( typeof coll.next == "function" )
var isArray = ( coll instanceof Array )
var hasFunc = ( typeof f == "function" )
var append = function(e){ res.push( hasFunc ? f(e) : e ) }
if( isIterator ){
while( coll.hasNext() ){ append( coll.next() ) }
} else if ( isArray ) {
coll.forEach(append)
} else {
throw new Error("unknown collection type " + coll )
}
return res
}
// mapping a Google Drive iterator
_map( DriveApp.getFolderById(id).getFiles(), function(file){ return file.getName() } )
// mapping over an array
_map( [1, 2, 3], function(n){ return n * 2 })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment