Last active
August 8, 2017 12:47
-
-
Save chrispsn/e286670716dbba7a43b3276f1aef84fe to your computer and use it in GitHub Desktop.
Testing ways to implement recordsets in vanilla JavaScript
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
/* | |
An object literal containing arrays and computed properties | |
can act as a recordset. | |
This would be a pain to edit in a text editor for long arrays, | |
but Mesh should make it intuitive via the grid interface. | |
*/ | |
const data = { | |
name: ['John Doe', 'Jane Smith'], | |
age: [30, 29], | |
get adult_yrs() {return this.age.map(x => x - 18)}, | |
} | |
// To consume the data: | |
function sum(arr) { return arr.reduce((sum, number) => sum + number, 0) }; | |
console.log(sum(data.adult_yrs)); | |
// prints: 23 | |
/* | |
If you wanted access to each record individually, | |
you could define a function or non-enumerable property as follows; | |
this is just a 'view' of the records and shouldn't impact much to do with Mesh, | |
but may make the structure easier to work with in the code: | |
*/ | |
// TODO query whether this should just be a function | |
// that takes the OOA and an index, and gets that record - | |
// can then produce other functions that do it for the whole OOA | |
// (may be less efficient though) | |
// Also, is there an equivalent that consumes a key instead of an integer? | |
// Kind of like an INDEX/MATCH or VLOOKUP... | |
const get_records = function (object_of_arrays) { | |
const keys = Object.keys(object_of_arrays); | |
// TODO account for case where no keys in object | |
// TODO should we verify that all arrays are the same length? | |
return object_of_arrays[keys[0]].map((_, idx) => { | |
const obj = {}; | |
for (let key of keys) { | |
obj[key] = object_of_arrays[key][idx]; | |
} | |
return obj; | |
}); | |
}; | |
Object.defineProperty(data, 'records', { | |
get: function() {return get_records(this)}, | |
enumerable: false, | |
}) | |
console.log(data.records); | |
// prints: | |
// [ { name: 'John Doe', age: 30, adult_yrs: 12 }, | |
// { name: 'Jane Smith', age: 29, adult_yrs: 11 } ] | |
/* | |
You could also cache the results of computed properties: | |
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get#Smart_self-overwriting_lazy_getters | |
*/ | |
/* | |
One disadvantage is that object keys technically don't have a guaranteed order, | |
so in theory Mesh's 'object of arrays' display function would require | |
the user to declare an order (via an arrays of keys) to be guaranteed | |
the grid view of the object doesn't change unexpectedly. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment