Expanding the JavaScript Map Data Type
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

53 lines
2.0 KiB

8 years ago
  1. var Map = function() { this.keys = []; this.items = new Object() }
  2. // PUT
  3. Map.prototype.put = function(key, value) { if (!(key in this.items)) { this.keys.push(key) } this.items[key] = value; }
  4. Map.prototype.putAll = function(obj) { for(item in obj) { this.put(item, obj[item]) } }
  5. // GET
  6. Map.prototype.get = function(key) { return this.items[key] }
  7. Map.prototype.getItems = function() { return this.items }
  8. Map.prototype.getKeys = function() { return this.keys }
  9. // OTHER
  10. Map.prototype.size = function() { return this.keys.length }
  11. Map.prototype.isEmpty = function() { return (this.keys.length == 0) }
  12. Map.prototype.containsKey = function(key) { return (this.items[key] !== undefined) }
  13. Map.prototype.clear = function() { this.keys = []; this.items = new Object() }
  14. // CLONE POLYFILL
  15. Object.prototype.clone = function() {
  16. var newObj = (this instanceof Array) ? [] : {};
  17. for (var i in this) {
  18. if (i == 'clone') continue;
  19. if (this[i] && typeof this[i] == "object") { newObj[i] = this[i].clone(); } else { newObj[i] = this[i]; }
  20. }
  21. return newObj;
  22. }
  23. var myMap = new Map()
  24. myMap.put("firstItem", true)
  25. myMap.put("secondItem", "doesn't matter")
  26. myMap.put("firstItem", "hello world!")
  27. myMap.putAll({"thirdItem": 1, "forthItem": 92.123})
  28. var items = myMap.getItems()
  29. var item = myMap.get("firstItem")
  30. var contains = myMap.containsKey("firstItem")
  31. var keys = myMap.getKeys()
  32. var size = myMap.size()
  33. var copy = myMap.clone()
  34. copy.put("firstItem", false)
  35. var clone = copy.getItems()
  36. var cloneKeys = copy.getKeys()
  37. var clear = myMap.clear()
  38. var shouldBeZero = myMap.size()
  39. console.log(items) // { "firstItem" : true, "secondItem": "doesn't matter" }
  40. console.log(item) // "hello world!"
  41. console.log(contains) // true
  42. console.log(keys) // [ "firstItem", "secondItem" ]
  43. console.log(size) // 2
  44. console.log(clone) // { "firstItem" : false, "secondItem": "doesn't matter" }
  45. console.log(cloneKeys) // [ "firstItem", "secondItem" ]
  46. console.log(shouldBeZero) // 0