Skip to content

Instantly share code, notes, and snippets.

@Anmo
Anmo / jsonp.js
Last active August 29, 2015 14:07 — forked from JosePedroDias/jsonp.js
window.jsonpCbs = { };
var jsonp = function( o ) {
var key = 'cb' + Math.floor( Math.random( ) * 100000 );
var sep = o.uri.indexOf( '?' ) < 0 ? '?' : '&';
var scriptEl = document.createElement( 'script' );
scriptEl.setAttribute( 'type' , 'text/javascript' );
scriptEl.setAttribute( 'src' , [ o.uri , sep , o.jsonp || 'jsonp' , '=jsonpCbs.' , key ].join( '' ) );
const split = (arr = [], n, ...arrs) => arr.length ? split(arr.slice(n), n, ...arrs, arr.slice(0, n)) : arrs
const splitIn = (arr = [], n) => split(arr, Math.ceil(arr.length / n))
const flat = (arr) => arr.reduce((a, b) => a.concat(b), [])
const mapParallel = (prom) => (arr) => Promise.all(arr.map(prom))
const mapSeries = (arr, prom, prevProm = Promise.resolve()) =>
Promise.all(arr.map(val => (prevProm = prevProm.then(() => prom(val)))))
const allLimit = (arr, limit) => ({ then: (prom) => mapSeries(split(arr, limit), mapParallel(prom)).then(flat) })