circular-buffer
Advanced tools
Comparing version
42
index.js
@@ -1,4 +0,40 @@ | ||
function CircularBuffer(cap){ | ||
if(!(this instanceof CircularBuffer))return new CircularBuffer(cap); | ||
//... | ||
function CircularBuffer(capacity){ | ||
if(!(this instanceof CircularBuffer))return new CircularBuffer(capacity); | ||
if(typeof capacity!="number"||capacity%1!=0||capacity<1) | ||
throw new TypeError("Invalid capacity"); | ||
var buffer=new Array(capacity),first=capacity-1,size=0; | ||
this.size=function(){return size;}; | ||
this.capacity=function(){return capacity;}; | ||
this.enq=function(value){ | ||
if(first>0)first--; else first=capacity-1; | ||
buffer[first]=value; | ||
if(size<capacity)size++; | ||
}; | ||
this.deq=function(){ | ||
if(size==0)throw new RangeError("CircularBuffer dequeue on empty buffer"); | ||
var value=buffer[first]; | ||
if(first==capacity-1)first=0; else first++; | ||
size--; | ||
return value; | ||
}; | ||
this.get=function(start,end){ | ||
if(size==0&&start==0&&(end==undefined||end==0))return []; | ||
if(typeof start!="number"||start%1!=0||start<0)throw new TypeError("Invalid start"); | ||
if(start>=size)throw new RangeError("Index past end of buffer: "+start); | ||
if(end==undefined)return buffer[(first+start)%capacity]; | ||
if(typeof end!="number"||end%1!=0||end<0)throw new TypeError("Invalid end"); | ||
if(end>=size)throw new RangeError("Index past end of buffer: "+end); | ||
var res=[],i; | ||
for(i=start;i<=end;i++)res.push(buffer[(first+i)%capacity]); | ||
return res; | ||
}; | ||
this.toarray=function(){ | ||
if(size==0)return []; | ||
return this.get(0,size-1); | ||
} | ||
} | ||
module.exports=CircularBuffer; |
{ | ||
"name": "circular-buffer", | ||
"version": "0.0.1", | ||
"version": "0.0.2", | ||
"description": "A NodeJS simple circular buffer implementation supporting indexing ", | ||
@@ -5,0 +5,0 @@ "main": "index.js", |
@@ -1,6 +0,6 @@ | ||
#NodeJS Circular Buffer | ||
# NodeJS Circular Buffer | ||
This is a simple [circular buffer](http://en.wikipedia.org/wiki/Circular_buffer) implementation for NodeJS. | ||
##Usage | ||
## Usage | ||
@@ -25,4 +25,4 @@ Below is a sample session with a circular buffer with this package. It should answer most questions. | ||
buf.toarray(); // -> [3,2] | ||
buf.deq(); | ||
buf.deq(); | ||
buf.deq(); // -> 3 | ||
buf.deq(); // -> 2 | ||
buf.toarray(); // -> [] | ||
@@ -32,3 +32,3 @@ buf.deq(); // -> throws RangeError("CircularBuffer dequeue on empty buffer") | ||
##Functions | ||
## Functions | ||
@@ -35,0 +35,0 @@ - `size()` -> `integer` |
Trivial Package
Supply chain riskPackages less than 10 lines of code are easily copied into your own project and may not warrant the additional supply chain risk of an external dependency.
Found 1 instance in 1 package
3833
49.32%36
800%0
-100%