Creating and Populating a Table From Scratch

I’ve made a sketch that stores and reads an array of CSV row strings from the browser’s local storage using storeItem() & getItem() respectively; then converts that array to p5.TableRow objects; and finally use p5.Table::addRow() to populate a p5.Table container: :card_index_dividers:

  1. http://p5js.org/reference/#/p5/getItem
  2. http://p5js.org/reference/#/p5.Table/addRow

Each mouse click adds a new p5.TableRow to the p5.Table container, updating the browser’s local storage as well. :computer_mouse:

Middle-click it in order to clear the p5.Table & browser’s local storage: :broom:

  1. http://p5js.org/reference/#/p5.Table/clearRows
  2. http://p5js.org/reference/#/p5/removeItem

This sketch can be checked running online at the link below: :link:


/**
 * Populate Table from Local Storage (v1.0.2)
 * GoToLoop (2019-Jul-11)
 *
 * Discourse.Processing.org/t/creating-and-populating-a-table-from-scratch/12658/3
 * Bl.ocks.org/GoSubRoutine/dabbc9371441720a07bd5de513a6b890
 */

'use strict';

const A_ASCII = 'A'.charCodeAt(),
      Z_ASCII = 'Z'.charCodeAt(),
      HASH = '#', COMMA = ',',
      STORAGE_NAME = 'MyCSVTableRows',
      SAVE_NAME = 'MyTable.csv',
      ALL_COLORS = 0x1000;

let table;

function setup() {
  createCanvas(200, 200).mousePressed(addRandomRow);
  noLoop();

  (table = new p5.Table).columns = ['name', 'x', 'y'];
  const storage = getItem(STORAGE_NAME);
  storage && populateTableFromStorage(table, storage);

  console.log(table);
}

function draw() {
  background(HASH + hex(~~random(ALL_COLORS), 3));
}

function addRandomRow() {
  if (mouseButton === CENTER)  return emptyTableAndItsStorage(table);

  const tr = table.addRow();
  tr.set(0, String.fromCharCode(random(A_ASCII, Z_ASCII + 1)));
  tr.set(1, ~~random(width));
  tr.set(2, ~~random(height));

  console.log(tr);
  storeItem(STORAGE_NAME, prepareTableRowsForStorage(table));
  redraw();
}

function emptyTableAndItsStorage(t) {
  t.clearRows();
  removeItem(STORAGE_NAME);
  return t;
}

function populateTableFromStorage(t, arr) {
  for (const s of arr)  t.addRow(new p5.TableRow(s));
  return t;
}

function prepareTableRowsForStorage({ rows }) {
  return rows.map(tableRowsToStorageConvertor);
}

function tableRowsToStorageConvertor({ arr }) {
  return arr.join();
}
1 Like