Created
October 13, 2013 07:16
-
-
Save aldonline/6959067 to your computer and use it in GitHub Desktop.
polymorphic map() over Google Apps Script iterators and Arrays.
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
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