I am using a JavaScript object as a dictionary, and wanted to make keys case-insensitive. I used Object.defineProperty()
to implement this:
Object.defineProperty(Object.prototype, "getKeyUpperCase", {
value: function(prop) {
for (var key in this) {
if (key.toUpperCase() === prop.toUpperCase()) {
return this[key];
};
};
},
enumerable: false
});
What is the time complexity of searching an object via key in JavaScript? I'm expecting the dictionary to hold around 1 million keys.
To me it looks like worst case would be O(n)
, best case would be O(1)
and average case would be O(n/2)
. Is this correct?
Would it be substantially more efficient to retrieve the object's keys as an array (Object.Keys(dictionary).map(function(key) return key.toUpperCase()).sort()
) to check if the key exists? Am I correct in saying that the average time complexity of this operation is O(log n)
?
Usage of the dictionary is along the lines of this:
var dictionary = {/* some million keys or so */};
var oldKey = someSmallArray[i];
var newValue = dictionary.getKeyUpperCase(oldKey.trim().toUpperCase());