Skip to content

Instantly share code, notes, and snippets.

@johnsonjo4531
Last active December 21, 2019 21:30
Show Gist options
  • Save johnsonjo4531/db57283f5c1c5a86642d6feb09623061 to your computer and use it in GitHub Desktop.
Save johnsonjo4531/db57283f5c1c5a86642d6feb09623061 to your computer and use it in GitHub Desktop.
Some GTOR functions
// Credit goes to github.com/kriskowal/gtor
// this is simply an esnext implementation of some of gtor
function deferred() {
const def = {}
def.promise = new Promise((resolve, reject) => {
def.resolve = resolve
def.reject = reject
})
return def
}
class PromiseQueue {
constructor (values) {
this.ends = deferred();
if (values) {
values.forEach(this.put, this);
}
}
put(value) {
const next = deferred();
this.ends.resolve({
head: value,
tail: next.promise
});
this.ends.resolve = next.resolve;
}
get () {
var result = this.ends.promise.then(node=>node.head);
this.ends.promise = this.ends.promise.then(node=>node.tail)
return result;
};
}
class PromiseBuffer {
constructor () {
var inbound = new PromiseQueue();
var outbound = new PromiseQueue();
this.out = {
next(value) {
outbound.put({
value,
done: false
});
return inbound.get();
},
return (value) {
outbound.put({
value,
done: true
});
return inbound.get();
},
throw (err) {
outbound.put(Promise.reject(err));
return inbound.get();
},
[Symbol.asyncIterator]() {
return this;
}
};
this.in = {
yield(value) {
inbound.put({
value,
done: false
});
return outbound.get();
},
return(value) {
inbound.put({
value,
done: true
});
return outbound.get();
},
throw(err) {
inbound.put(Promise.reject(err));
return outbound.get();
}
}
}
[Symbol.asyncIterator] () {
return this.out
}
}
export {
PromiseBuffer,
PromiseQueue
};
The MIT License (MIT)
Copyright (c) 2014 Kris Kowal, johnsonjo4531
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment