Reputation: 4942
Background
I have an array of objects that are all the same type.
I've created a class for handling lookups on arrays of all the same type. The point of the class is to prevent iterating through the array more than you need to each time you look for an object based on it's property.
The bare bones of my lookup class looks something like this. So you can understand what it does.
/**
* @constructor
* @param {Array} items An array of all the same type of item.
*/
titan.structs.IndexedLookup = function (items) {};
/**
* Get by property
* @param {String} property The property name.
* @param {String|Number} value The property value.
* @returns {Object|null}
*/
titan.structs.IndexedLookup.prototype.getByProperty =
function (property, value) {};
Problem
I want use the last line of this
var lookup = new titan.structs.IndexedLookup(myArrayOfItems);
// Lookup by property 'id'
var item = lookup.getByProperty("id", 27);
I can't think of any clever way of getting the actual property name that the advanced compiler has assigned instead of "id".
Remarks
I'm not looking for a solution of using properties in quotes on the object types as that requires prior knowledge when designing the object class that it will be used as a lookup property later in some unknown component.
Upvotes: 1
Views: 537
Reputation: 5468
There are a number of solutions:
Two approaches that prevent renaming:
use property quoting consistently:
item['id'] = 2;
lookup.getByProperty('id', 2);
add an extern declaration:
Object.prototype.id;
Two approaches that allow renaming:
Add a declaration for JSCompiler_renameProperty like:
function JSCompiler_renameProperty(prop) { return prop }
and use it like so:
lookup.getByProperty(JSCompiler_renameProperty("id"), 27);
this is not good does work well with type based optimizations.
Use goog.reflect.object from the closure library:
var idPropName = (goog.object.transpose(goog.reflect.object(MyType, id: 1)))[1];
This allows you to specify the type associated with the property and works well with the type based optimizations.
Upvotes: 2
Reputation: 14411
This is a difficult probblem and there isn't a great solution out there. You can view some of the discussions: Tests for Property Existance with Renaming
Normally I find ways to refactor my code to handle the problem differently.
I encourage you to open an issue in the Closure-compiler project requesting a feature supporting this.
Upvotes: 2