pastelli - Code Cookbook & Code Recipies
I always forget tiny code snippets I need, so I made a blog to keep up with them all.
TV Static Canvas Animation
- - Matthew Callis

A simple TVStatic like animation I made for sfc.fm, not very realistic but might expand it in the future. If you want to take it further have a look at the CRT Simulation library.

class TVStatic {
  constructor(options = {}) {
    this.canvas = options.canvas;

    if (!this.canvas) {
      throw new Error('No canvas element provided.');
    }

    this.ctx = this.canvas.getContext('2d');
    this.toggle = true;
    this.pause = options.pause || false;

    this.loop = this.loop.bind(this);
    this.noise = this.noise.bind(this);
    this.pauseLoop = this.pauseLoop.bind(this);

    return this;
  }

  noise() {
    const w = this.ctx.canvas.width;
    const h = this.ctx.canvas.height;
    const image_data = this.ctx.createImageData(w, h);
    const buffer32 = new Uint32Array(image_data.data.buffer);
    const len = buffer32.length;

    for (let i = 0; i < len; i++) {
      if (Math.random() < 0.5) {
        buffer32[i] = 0xff000000; // 4278190080
      }
    }

    this.ctx.putImageData(image_data, 0, 0);
  }

  pauseLoop() {
    return this.pause = !this.pause;
  }

  loop() {
    if (this.pause) {
      return;
    }

    // added toggle to get 30 FPS instead of 60 FPS
    this.toggle = !this.toggle;
    if (this.toggle) {
      requestAnimationFrame(this.loop);
      return;
    }
    this.noise();
    requestAnimationFrame(this.loop);
  }
}

Example

Ramda.js - Toggle Array Item
- - Matthew Callis

Toggle an array value by adding it to the array when it is not present, and removing from the array it when it is present. Done using Ramda.js.

const items = ['a', 'b', 'c', 'd', 'e'];
const toggleValue = ifElse(
  contains(__, items),
  without(__, items),
  append(__, items)
);

toggleValue('f');
    ["a", "b", "c", "d", "e", "f"]

toggleValue('a');
    ["b", "c", "d", "e"]

Example

Ramda.js - Parse Query String
- - Matthew Callis

Parsing of a query string with Ramda.js.

let query_string = '?p=ハッカー製&auccat=22844&alocale=0jp&acc=jp';

// First to Last
pipe(tail, split('&'),  map(split('=')), fromPairs)(query_string);
    { acc: 'jp', alocale: '0jp', auccat: '22844', p: 'ハッカー製' }

// Last to First
compose(fromPairs, map(split('=')), split('&'), tail)(query_string);
    { acc: 'jp', alocale: '0jp', auccat: '22844', p: 'ハッカー製' }

// Check for question mark first.
const cleanQuery = ifElse(
  pipe(head, equals('?')),
  tail,
  identity
);

query_string = '?_from=R40&_nkw=mario&_sacat=0';
pipe(
  cleanQuery,
  split('&'),
  map(split('=')),
  fromPairs
)(query_string);
    { _from: 'R40', _nkw: 'mario', _sacat: '0' }

Example