Populate Table from Local Storage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
height: 204 | |
scrolling: no | |
border: no | |
license: cc-by-4.0 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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