Skip to content

Instantly share code, notes, and snippets.

@GoSubRoutine
Last active November 8, 2019 13:48
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save GoSubRoutine/dabbc9371441720a07bd5de513a6b890 to your computer and use it in GitHub Desktop.
Populate Table from Local Storage
height: 204
scrolling: no
border: no
license: cc-by-4.0
<!DOCTYPE html>
<meta charset=utf-8>
<meta name=viewport content=width=device-width,initial-scale=1>
<script async src=https://cdn.JsDelivr.net/npm/p5></script>
<script defer src=sketch.js></script>
/**
* 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();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment