Skip to content

Instantly share code, notes, and snippets.

@chrispsn
Last active June 6, 2018 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrispsn/e377bc250beb0feba0ab8783225bc388 to your computer and use it in GitHub Desktop.
Save chrispsn/e377bc250beb0feba0ab8783225bc388 to your computer and use it in GitHub Desktop.
A table that has cells while also allowing arbitrary (albeit user defined) length. Aim is IE11 compatibility.
/* Setup */
var _defProp = Object.defineProperty;
var Table = {};
function tabulate(o) {
var entries = []; Object.keys(o).forEach(function(h) {
if (h !== "length") {entries.push([h, o[h].values, o[h].default])}
});
if (o.length === undefined) {
o.length = Math.max(entries.map(function(e) {return e[1].length}));
};
Object.setPrototypeOf(o, Array.prototype);
entries.forEach(function(pair) {
var h = pair[0];
delete o[h];
_defProp(o, h, {get: function() {return this.map(function(r) {return r[h]})}});
});
var row, length = o.length;
for (var i = 0; i < length; i++) {
o[i] = row = {};
entries.forEach(function(pair) {
var h = pair[0], val = pair[1][i], j = i;
var c = (val !== undefined) ? val : pair[2];
_defProp(row, h, {configurable: true, get: function() {
delete this[h];
return this[h] = (typeof c === "function") ? c.call(o, j) : c;
}});
})
};
};
/* Example */
var someTable = {
__proto__: Table,
// length: 4,
tableColumn: {
values: [
/* hardcode */ 7,
/* use default */ ,
/* formula */ function(rowIdx) {return this[rowIdx - 1].tableColumn + 1},
],
default: function(rowIdx) {return rowIdx * 2},
}
}
tabulate(someTable);
console.log(someTable[0].tableColumn); // 7
console.log(someTable[1].tableColumn); // 2
console.log(someTable[2].tableColumn); // 3
console.log(someTable.tableColumn); // [7, 2, 3], or with length = 4, [7, 2, 3, 6]
console.log("Length:", someTable.length); // 3, or with length = 4, 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment