Skip to content

Instantly share code, notes, and snippets.

@Vinorcola
Created September 22, 2015 22:08
Show Gist options
  • Save Vinorcola/ce9a4986d3983e106b66 to your computer and use it in GitHub Desktop.
Save Vinorcola/ce9a4986d3983e106b66 to your computer and use it in GitHub Desktop.
Node - buffer with native promises
'use strict'
var config = {
bufferMaxSize: 1,
}
var _pushPromise
var _pullPromise
var _content = []
function doPush(data, resolve, reject)
{
if (_content.length >= config.bufferMaxSize)
{
reject()
}
else
{
_content.push(data)
resolve()
}
}
function doPull(resolve, reject)
{
if (_content.length < 1)
{
reject()
}
else
{
resolve(_content.shift())
}
}
var self = {
push: function(data)
{
return new Promise(function(resolve, reject)
{
// If the buffer is full, we keep the push request aside while waiting for a new pull request. If there
// already is a waiting push request, we reject the current one.
if (_content.length >= config.bufferMaxSize)
{
if (_pushPromise !== undefined)
{
reject()
return
}
_pushPromise = {
resolve: resolve,
reject: reject,
data: data,
}
return
}
// We push the data.
doPush(data, resolve, reject)
// If there is a pending pull request, we resolve it.
if (_pullPromise !== undefined)
{
var ppResolve = _pullPromise.resolve
var ppReject = _pullPromise.reject
_pullPromise = undefined
doPull(ppResolve, ppReject)
}
})
},
pull: function()
{
return new Promise(function(resolve, reject)
{
// If the buffer is empty, we keep the pull request aside while waiting for a new push request. If there
// already is a waiting pull request, we reject the current one.
if (_content.length < 1)
{
if (_pullPromise !== undefined)
{
reject()
return
}
_pullPromise = {
resolve: resolve,
reject: reject,
}
return
}
// We pull the data.
doPull(resolve, reject)
// If there is a pending push request, we resolve it.
if (_pushPromise !== undefined)
{
var ppResolve = _pushPromise.resolve
var ppReject = _pushPromise.reject
var ppData = _pushPromise.data
_pushPromise = undefined
doPush(ppData, ppResolve, ppReject)
}
})
},
getFreeSpace: function()
{
return config.bufferMaxSize - _content.length
},
clear: function()
{
_content.length = 0
if (_pushPromise !== undefined)
{
_pushPromise.reject()
_pushPromise = undefined
}
if (_pullPromise !== undefined)
{
_pullPromise.reject()
_pullPromise == undefined
}
},
}
module.exports = self
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment