JavaScript Data Buffer

Written 5 months and 1 week ago

Buffers are typically used when processing data is slower than the rate at which it is received.

Not to be confused with…

Node.js implements a Buffer for the purpose of working with binary streams.

JavaScript implements an ArrayBuffer which is a fixed size raw binary data buffer to be used with typed arrays.

My DataBuffer

class DataBuffer extends EventEmitter {
    constructor (options={}) {
        super();
        const {
            size = 10,
        } = options;
        this.buffer = [];
        this.size = size;
    }

    insert(data) {
        this.buffer.push(data);
        if (this.buffer.length >= this.size) {
            this.flush();
        }
    }

    flush() {
        const result = this.buffer;
        this.emit('flush', result)
        this.buffer = [];
        return result;
    }
}

Usage

const dataBuffer = new DataBuffer({ size: 5 });
dataBuffer.on('flush', console.log);

dataBuffer.insert('one');
dataBuffer.insert('two');
dataBuffer.insert('three');
dataBuffer.insert('four');
dataBuffer.insert('five');
// 'flush' is emitted with ['one', 'two', 'three', 'four', 'five']

dataBuffer.insert('six');
dataBuffer.insert('seven');
dataBuffer.flush();
// => ['six', 'seven']
// 'flush' is emitted with ['six', 'seven']

Other Articles

Storing Private Keys on Encrypted Flash Memory

written 5 months and 2 days ago

Storing my SSH key on flash memory in an encrypted VeraCrypt container.
Read more

MailChimp Subscription with JavaScript

written 5 months and 5 days ago

Client-side MailChimp subscription without redirecting the user away.
Read more

MongoDB Auditing Documents using Change Streams

written 5 months and 1 week ago

Versioning documents in MongoDB by listening to changes using the change streams listener. It's ideal for audit logs or auditing.
Read more

Discussion