Skip to content

Instantly share code, notes, and snippets.

View jaawerth's full-sized avatar

Jesse Wertheim jaawerth

View GitHub Profile
@jaawerth
jaawerth / allowcors.js
Last active August 29, 2015 14:13
Super simple middleware for allowing CORS from express
app.use(allowCrossDomain); // Use below function as a middleware for your requests
function allowCrossDomain(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
// intercept OPTIONS method
if ('OPTIONS' == req.method) {
res.send(200);
@jaawerth
jaawerth / iterator.concat.js
Last active August 29, 2015 14:19
jaawerth's iterator concat (es6 generator-based)
/* Concatenate iterators by wrapping them in a "parent" iterator.
* When it's consumed, to the outside world it will appear as a single
* iterator. Allows for easily-implemented lazy evaluation and immutable
* transformations.
*/
import toIterator from './iterator';
import { isArray, isIterable, isIterator } from '../types';
function concat(...items) {
@jaawerth
jaawerth / promise-series.js
Last active September 4, 2018 21:07
Run a list of functions in series, returning a pjromise that resolves to an array of results.
'use strict';
/*
* run promises in sequence, return an array of results.
* Returns a promise that resolves to an array of results, where funcs[i]() -> results[i]
*/
function asyncSeries(...funcs) {
return aggregate([], funcs);
}
@jaawerth
jaawerth / timeout-promise.js
Created October 18, 2015 02:08
Example of how to write a version of setTimeout that returns a promise
function timeout(fn, delay) {
var args = Array.prototype.slice(arguments, 2);
return new Promise(function(resolve, reject) {
setTimeout(function() {
try {
resolve(fn.apply(null, args));
} catch(e) {
reject(e);
{
"name": "promise-map",
"version": "1.0.0",
"main": "./promise-map.js"
}
@jaawerth
jaawerth / README.md
Last active February 15, 2023 05:45
Example implementation of using generators the "spawn" function for JavaScript coroutines in ES6, for async/await functionality

JavaScript coroutines and "spawn"

In ES2017, we have async/await for unwrapping promises. However, this is just syntastic sugar for the use of coroutines, which are already available in ES6 (see the recommended modules tj/co and Bluebird's Promise.coroutine()).

Below is a sample implementation of spawn showing how it works. It takes a generator function, inside of which yield can be used to unwrap promises for synchronous-style code. spawn always returns a promise.

Try it yourself!

You can install this gist via npm to tinker with it yourself, or copy/paste the function into any environment that supports generators.

**IMPORTANT: Use this code only for tinkering and education purposes, not for use in a real project. While you're free to do so, it's a MUCH beter practice to use an existing, published module for such functionality, such as the

@jaawerth
jaawerth / parse-querystng.js
Last active November 11, 2015 18:37
simple function for parser a URL's querystring into an object of key-value pairs
function parse(qs) {
return qs.replace(/^\?/, '').split('&').reduce(function(col, pairStr) {
// pairStr is of form `foo=bar`
var pair = pairStr.split('=').map(decodeURIComponent);
col[pair[0]] = pair[1];
return col;
}, {});
}
@jaawerth
jaawerth / throttle.js
Created October 28, 2015 07:06
A basic throttle implementation
/* Simple implementation of "throttle".
* Option object has boolean properties 'trailing' and 'leading', where 'leading'
* defaults to true.
**/
function throttle(fn, period, opts) {
opts = opts || {};
var leading = opts.leading === false ? false : true; // defaults to true
var trailing = !!opts.trailing; // defaults to false
var args, cached;
cleanUpOriginList(){
var i;
for (i = this.originList.length; i--;) {
delete this.originList[i].id;
delete this.originList[i].createdBy;
delete this.originList[i].modifiedBy;
delete this.originList[i].createdDate;
delete this.originList[i].createdDate;
delete this.originList[i].modifiedDate;
if (this.originList[i].targetName === '') {
@jaawerth
jaawerth / compose.es6.js
Last active October 17, 2020 08:08
ES5 and ES6 implementations of compose - readable implementation, not optimized
function compose(...fnArgs) {
const [first, ...funcs] = fnArgs.reverse();
return function(...args) {
return funcs.reduce((res, fn) => fn(res), first(...args));
};
}