admin管理员组文章数量:1399926
Suppose I'm visiting nodes in a graph data structure. As I visit each node, I would add it to a "visited" list. It would be desirable to have an O(1) lookup to verify that I don't visit the same node more than once.
Of course, if each node has an associated value, I could use a regular JavaScript object (hash table) to store my "visited" list, but suppose I want to be agnostic to whether the node can evaluate to a string or not. Is there a JavaScript data structure that would support O(1) lookups for objects? How could I implement one?
Suppose I'm visiting nodes in a graph data structure. As I visit each node, I would add it to a "visited" list. It would be desirable to have an O(1) lookup to verify that I don't visit the same node more than once.
Of course, if each node has an associated value, I could use a regular JavaScript object (hash table) to store my "visited" list, but suppose I want to be agnostic to whether the node can evaluate to a string or not. Is there a JavaScript data structure that would support O(1) lookups for objects? How could I implement one?
Share Improve this question asked Oct 16, 2015 at 21:21 BlackhawkBlackhawk 6,1504 gold badges29 silver badges59 bronze badges 8-
Then use ES2015
Set
(orWeakMap
whichever suits better) – zerkms Commented Oct 16, 2015 at 21:22 - you can push to an array and use array.indexOf to see if a node ref is in the list, but that's probably slow. you could also set an invisible prop on the node itself, which is fast, but might break things depending on setup. – dandavis Commented Oct 16, 2015 at 21:31
- @zerkms I just checked my pany-mandated browser against the patibility list here and cried a little bit :'( – Blackhawk Commented Oct 16, 2015 at 21:40
- @Blackhawk babeljs.io – zerkms Commented Oct 16, 2015 at 21:47
- @zerkms interesting... I'm going to take a look and see if I can figure out how they've implemented the functionality... – Blackhawk Commented Oct 16, 2015 at 21:53
2 Answers
Reset to default 7You can either use the Set
or WeakMap
both added in ES2015.
And you don't need to wait for the browser support, since transpilers like babel have standard-pliant polyfills.
To do O(1) lookups, you need to use a hash set. There is no hash set in native javascript, but there is a hash map (plain object). You can emulate a hash set by checking if the object contains the key. Your value needs to implement the toString
method.
var Set = function () {}
Set.prototype.contains = function (v) {
return (v.toString() in this);
}
Set.prototype.add = function (v) {
this[v.toString()] = true;
}
Set.prototype.remove = function (v) {
delete this[v.toString()];
}
本文标签: javascriptData structure for objects with O(1) lookupStack Overflow
版权声明:本文标题:javascript - Data structure for objects with O(1) lookup? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744209551a2595355.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论