| 96 | |
| 97 | // Wrap a given function to support batch processing |
| 98 | function batch(func, processor, options) { |
| 99 | // func is optional |
| 100 | if(arguments.length < 3) { |
| 101 | options = processor; |
| 102 | processor = func; |
| 103 | func = _.identity; |
| 104 | } |
| 105 | |
| 106 | // Parse and default args |
| 107 | options = options || {}; |
| 108 | |
| 109 | // If no debounce options was passed set n to 1 |
| 110 | options.n = options.debounce ? options.n : 1; |
| 111 | |
| 112 | // A queue to store the return value of "func" |
| 113 | // that will then be processed by "processor" |
| 114 | var queue = []; |
| 115 | |
| 116 | var processQueue = function processQueue() { |
| 117 | // Let the processor, process all the data in the queue |
| 118 | processor(queue); |
| 119 | |
| 120 | // Empty queue |
| 121 | queue = []; |
| 122 | }; |
| 123 | |
| 124 | var debounced = (options.debounce !== undefined) ? |
| 125 | _.debounce(processQueue, options.debounce) : |
| 126 | processQueue; |
| 127 | |
| 128 | return function() { |
| 129 | var value = func.apply(null, arguments); |
| 130 | queue.push(value); |
| 131 | |
| 132 | // Call our debounced queue processor |
| 133 | debounced(); |
| 134 | |
| 135 | // Force call if queue is getting to big |
| 136 | if(options.n && queue.length >= options.n) { |
| 137 | processQueue(); |
| 138 | } |
| 139 | |
| 140 | return value; |
| 141 | }; |
| 142 | } |
| 143 | |
| 144 | var btoa = function(s) { |
| 145 | return (new Buffer(s)).toString('base64'); |