pathterminuspages/snippets/aboutcontactabout me

Implementing a dictionary in JavaScript

15-01-2018

I suddently needed a dictionary in JS. JS has objects which almost are dictionaries. You can actually foreach them, I found out. But given backward compatibility and the fact that a dictionary iterable dictionary isn't that hard to create, I decided to build one. So here we go:

var Dictionary = function(){ var tail = null; var head = null; var dict = {}; var add = function(key,elm){ if(dict[key] !== undefined){ dict[key].val = elm; } else { dict[key] = {}; dict[key].val = elm; dict[key].key = key; dict[key].next = null; if(tail !== null){ tail.next = dict[key]; } tail = dict[key]; } if(head === null){ head = tail; } }; var containsKey = function(key){ return dict[key] !== undefined; }; var get = function(key){ if(dict[key] !== undefined){ return dict[key].val; } return null; }; var foreach = function(f){ var h0 = head; while(h0 !== null){ f(h0.key,h0.val); h0 = h0.next; } }; return { add:add, containsKey:containsKey, get:get, foreach:foreach }; };

Commence testing:

var d1 = new Dictionary(); d1.add("item1","val1"); d1.add("item2","val2"); d1.add("item3","val3"); d1.add("item4","val4"); out1.innerHTML = "D1<br>"; out1.innerHTML += d1.containsKey("item1") + "<br>"; out1.innerHTML += d1.containsKey("item item") + "<br>"; out1.innerHTML += d1.get("item1") + "<br>"; out1.innerHTML += "foreach:<br>"; d1.foreach(function(key,val){ out1.innerHTML += key + " -> " + val + "<br>"; }); var d2 = new Dictionary(); out2.innerHTML = "D2<br>"; out2.innerHTML += d2.containsKey("some key") + "<br>"; out2.innerHTML += d2.get("some other key") + "<br>"; d2.foreach(function(elm){ out2.innerHTML += elm + "<br>"; });

And we get:

D1 true false val1 foreach: item1 -> val1 item2 -> val2 item3 -> val3 item4 -> val4 D2 false null

...

CommentsGuest Name:Comment: