Associative Array - advance


/ Published in: JavaScript
Save to your folder(s)

/* ---===[ EXAMPLE ]===--- */

var TT = new AssociativeArray();

TT.add("k-1", "Value 1");
TT.add("k-2", "Value 2");
TT.add("k-3", "Value 3");
TT.add("k-4", "Value 4");

alert(TT.to_string());


Copy this code and paste it in your HTML
  1. var AssociativeArray = function() {
  2.  
  3. this.hash = new Array();
  4.  
  5. this.size = function() {
  6. var size = 0;
  7. for(var i in this.hash) {
  8. if(this.hash[i] != null) {
  9. size++;
  10. }
  11. }
  12. return size;
  13. };
  14.  
  15. this.clear = function() {
  16. this.hash = new Array();
  17. };
  18.  
  19. this.add = function(key, value) {
  20. if(key == null || value == null) {
  21. throw "NullPointerException { \"" + key + "\" : \"" + value + "\" }";
  22. }
  23. else {
  24. this.hash[key] = value;
  25. }
  26. };
  27.  
  28. this.get = function(key) {
  29. return this.hash[key];
  30. };
  31.  
  32. this.remove = function() {
  33. var value = this.hash[key];
  34. this.hash[key] = null;
  35. return value;
  36. };
  37.  
  38. this.contains_key = function(key) {
  39. var exist = false;
  40. for(var i in this.hash) {
  41. if(i == key && this.hash[i] != null) {
  42. exist = true;
  43. break;
  44. }
  45. }
  46. return exist;
  47. };
  48.  
  49. this.contains_value = function(value) {
  50. var contains = false;
  51. if(value != null) {
  52. for(var i in this.hash) {
  53. if(this.hash[i] == value) {
  54. contains = true;
  55. break;
  56. }
  57. }
  58. }
  59. return contains;
  60. };
  61.  
  62. this.is_empty = function() {
  63. return (parseInt(this.size()) == 0) ? true : false;
  64. };
  65.  
  66. this.keys = function() {
  67. var keys = new Array();
  68. for(var i in this.hash) {
  69. if(this.hash[i] != null) {
  70. keys.push(i);
  71. }
  72. }
  73. return keys;
  74. };
  75.  
  76. this.values = function() {
  77. var values = new Array();
  78. for(var i in this.hash) {
  79. if(this.hash[i] != null) {
  80. values.push(this.hash[i]);
  81. }
  82. }
  83. return values;
  84. };
  85.  
  86. this.to_string = function() {
  87. var string = "{\"array\": [\n";
  88. for(var i in this.hash) {
  89. if(this.hash[i] != null) {
  90. string += "\t{ \"" + i + "\" : \"" + this.hash[i] + "\" },\n";
  91. }
  92. }
  93. return string += "]}";
  94. };
  95. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.