4 ms·
Hash Tables in JavaScript
- kaesve 11y agoThe article does not implement a hash table, it just is a wrapper around javascript objects that keeps count of the number of properties. The example code is buggy (it leaks `previous` to global scope) and not particularly elegant. I would not bother with trying to use something like this.
- lkey 11y agoA couple of notes, since this article appears quite dated. var hash = Object.create(null) creates an object free of inherited properties, this obviates most of the need for a wrapper class for the "I just want an associative array" case. For the "keys", "values", and "each" methods In modern JS one could simply call Object.keys(hash) Object.keys(hash).map(function(key) { return hash[key] }) Object.keys(hash).forEach(function(key) { fn(key, hash[key]) }) respectively. Or as the article suggests, simply use a library like Lodash for this kind of general purpose iteration.
- jestar_jokin 11y agoIf you don't mind pulling in the other stuff, Google Closure has provided a Map (hash map/hash table) implementation for a while. You can use the Closure Compiler or ClosureBuilder to ensure you only serve the necessary Closure modules. https://closure-library.googlecode.com/git-history/docs/class_goog_structs_Map.html https://closure-library.googlecode.com/git-history/docs/clas... https://developers.google.com/closure/library/docs/closurebuilder https://developers.google.com/closure/library/docs/closurebu...
- dyoo1979 11y ago... Yikes. The advice in this post is unfortunately naive. It's dangerous to allow arbitrary object attribute key content. Some object properties in JavaScript must be treated as reserved. Allowing arbitrary access to key names has unexpected repercussions. For example, consider "prototype" or "hasOwnProperty" as key names. See: http://www.devthought.com/2012/01/18/an-object-is-not-a-hash/ http://www.devthought.com/2012/01/18/an-object-is-not-a-hash... for more details. So I'd +1 jestar_jokin's advice: use code that's been well-tested. The code presented in the original poster's "Hash Tables in Javascript" article does not look robust.