JSFiddle - React, Tailwind, and code Playground
JavaScript
//
// Fast object iterators in JavaScript.
// See: http://stackoverflow.com/questions/1573593/whats-the-fastest-way-to-iterate-over-an-objects-properties-in-javascript/25700742#25700742
//
// ####################################################################################
// Initial preparation (define once, then re-use for the life-time of our applciation)
// ####################################################################################
/**
* Init #1: Compile iterator function for a specific type.
*/
var compileIterator = function(typeProperties) {
// pre-compile constant iteration over object properties
var iteratorFunStr = '(function(obj, cb) {\n';
for (var i = 0; i < typeProperties.length; ++i) {
// call callback on i'th property, passing key and value
iteratorFunStr += 'cb(\'' + typeProperties[i] + '\', obj.' + typeProperties[i] + ');\n';
};
iteratorFunStr += '})';
// actually compile and return the function
return eval(iteratorFunStr);
};
// Init #2: Construct type-information and iterator for a performance-critical type
var declareType = function(propertyNamesInOrder) {
var self = {
// "type description": listing all properties, in specific order
propertyNamesInOrder: propertyNamesInOrder,
// compile iterator function for this specific type
forEach: compileIterator(propertyNamesInOrder),
// create new object with given properties and matching initial values
construct: function(initialValues) {
var o = { _type: self }; // also store type information
propertyNamesInOrder.forEach((name) => o[name] = initialValues[name]);
return o;
}
};
return self;
};
// Init #3: Declare new type
var MyType = declareType(['a', 'b', 'c']);
// ####################################################################################
// Run-time stuff (we might do these things again and again during run-time)
//...