Skip to content

Instantly share code, notes, and snippets.

@MisterJames
Last active December 24, 2015 05:09
Show Gist options
  • Select an option

  • Save MisterJames/6748923 to your computer and use it in GitHub Desktop.

Select an option

Save MisterJames/6748923 to your computer and use it in GitHub Desktop.
A simple JavaScript function that gives you a way to maintain a unique list of strings, by a string key, similar in function to a c# dictionary<string, List<string>>.
"use strict";
$.stringDictionary = function () {
this.data = {};
// adds a unique value to the array stored in 'key'
this.add = function (key, value) {
var editors = this.data[key];
if (editors) {
if (!this.contains(key, value)) {
this.data[key].push(value);
}
} else {
this.data[key] = new Array();
this.data[key].push(value);
}
};
// attempts to remove the value from the array in 'key'
this.remove = function (key, value) {
var values = this.data[key];
var index = values.indexOf(value);
if (index > -1) {
values.splice(index, 1);
}
};
// dumps the entire map to the console
this.dumpFields = function () {
console.debug(this.data);
for (var key in this.data) {
var values = this.data[key];
for (var index in values) {
var msg = key + ':' + values[index];
console.debug(msg);
$("#foo").append($('<p>').html(msg));
}
}
console.debug('-----');
}
// checks to see if a value is present in the map
this.contains = function (key, value) {
return (this.data[key].indexOf(value) > -1);
}
// helper method to get the list of keys
this.keys = function(){
var result = new Array();
for (var key in this.data) {
result.push(key);
}
return result;
}
// clears all the data
this.clear = function () {
this.data = {};
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment