Message queue class

Recently at work I needed to implement a message queue. I like the pattern and I think I will need it more often in the future. I recreated the message queue with a class for personal reference and study purposes.

message-queue

I absolutely like some of the new features: for example proper ‘this’ binding with the arrow functions and parameter defaults in function.

Code

you can see the full code below, or get the example from my github account

/**
 * MessageQueue create notification messages
 */
class MessageQueue {


    /**
     * constructor optional container and delay
     */
    constructor(container = document.getElementById('messageContainer'), delay = 5000) {
        this.messageQueue = [];
        this.container = container;
        this.delay = delay;
    }

    clearMessages() {
        this.container.innerHTML = '';
    }

    displayMessages() {
        let messageFrag = document.createElement('div');

        // clear
        this.clearMessages();

        for (let index = 0; index < this.messageQueue.length; index++) {
            let message = document.createTextNode(this.messageQueue[index].text);
            let flash = document.createElement('div');

            flash.classList.add('flash-message');
            flash.classList.add(this.messageQueue[index].msgType);
            flash.appendChild(message);

            messageFrag.appendChild(flash);

        }
        this.container.appendChild(messageFrag);
    }

    remove() {
        this.messageQueue.shift();
        this.displayMessages();
    }

    /**
     * add messages optional type (CSS class)
     */
    add(message, type = 'error') {
        let msg = {
            text: message,
            index: this.messageQueue.length,
            msgType: type,
        };

        setTimeout(() => this.remove(), this.delay);

        this.messageQueue.push(msg);
        this.displayMessages();
    }
}

Feel free to modify and extend the code, to run the code you need to install babel-cli and run the following watch statement

babel messagequeue.js --watch --out-file messagequeue-compiled.js

Espruino Pico received

I was awaiting it for some time, until yesterday. It is amazing easy to play with hardware with espruino. It is easy to transfer my daily web workflow onto hardware. Still lots of thing to learn, hence I feel the the learning curve of Espruino is a very rewarding one ;-). See below for my first very small tinkering project with the Espruino Pico.

Controlling servo with distance sensor

IMG_6468

Code

var servo = require("servo").connect(B7);

var sensor = require("HC-SR04").connect(B3,B4,function(dist) {
  //module output in cm
  if(dist <= 20){
    servo.move(0.5, 500);
  }
  if(dist >= 30){
    servo.move(1, 500);
  }
});
setInterval(function() {
  //send pulse
  sensor.trigger(); 
}, 500);

As you can see the code is very compact. The possibility to console.log sensor reading in the console is priceless!