map.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // Public domain
  2. function Map(compareFunction) {
  3. this.keyArray = [];
  4. this.valArray = [];
  5. this.compareFunction = compareFunction;
  6. }
  7. Map.prototype.put = function(key, val) {
  8. var elementIndex = this.findKey(key);
  9. if (elementIndex === (-1)) {
  10. this.keyArray.push(key);
  11. this.valArray.push(val);
  12. } else {
  13. this.valArray[elementIndex] = val;
  14. }
  15. };
  16. Map.prototype.get = function(key, def) {
  17. var result = def;
  18. var elementIndex = this.findKey(key);
  19. if (elementIndex !== (-1)) {
  20. result = this.valArray[elementIndex];
  21. }
  22. return result;
  23. };
  24. Map.prototype.remove = function(key) {
  25. var result = null;
  26. var elementIndex = this.findKey(key);
  27. if (elementIndex !== (-1)) {
  28. this.keyArray = this.keyArray.removeAt(elementIndex);
  29. this.valArray = this.valArray.removeAt(elementIndex);
  30. }
  31. return;
  32. };
  33. Map.prototype.size = function() {
  34. return (this.keyArray.length);
  35. };
  36. Map.prototype.clear = function() {
  37. for ( var i = 0; i < this.keyArray.length; i++) {
  38. this.keyArray.pop();
  39. this.valArray.pop();
  40. }
  41. };
  42. Map.prototype.getKeys = function() {
  43. return (this.keyArray);
  44. };
  45. Map.prototype.getValues = function() {
  46. return (this.valArray);
  47. };
  48. Map.prototype.toString = function() {
  49. var result = "";
  50. for ( var i = 0; i < this.keyArray.length; i++) {
  51. result += "Key: " + this.keyArray[i] + "\tValue: " + this.valArray[i]
  52. + "\n";
  53. }
  54. return result;
  55. };
  56. Map.prototype.hasKey = function(key) {
  57. return this.findKey(key)!==-1;
  58. };
  59. Map.prototype.findKey = function(key) {
  60. var result = (-1);
  61. for ( var i = 0; i < this.keyArray.length; i++) {
  62. if (typeof(this.compareFunction)!=="undefined") {
  63. if (this.compareFunction(this.keyArray[i], key)) {
  64. result = i;
  65. break;
  66. }
  67. }
  68. else {
  69. if (this.keyArray[i] == key) {
  70. result = i;
  71. break;
  72. }
  73. }
  74. }
  75. return result;
  76. };
  77. Array.prototype.removeAt = function(index) {
  78. var part1 = this.slice(0, index);
  79. var part2 = this.slice(index + 1);
  80. return (part1.concat(part2));
  81. };