Last active
August 29, 2015 14:07
-
-
Save lnsp/e07c2931594494261f9d to your computer and use it in GitHub Desktop.
JavaScript hash map implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var JSL = JSL || {}; | |
JSL.HashMap = function () { | |
"use strict"; | |
var keys = [], | |
values = []; | |
function indexOf(key) { | |
var i = 0; | |
if (keys.indexOf !== undefined) { | |
return keys.indexOf(key); | |
} | |
for (i = 0; i < keys.length; i += 1) { | |
if (key === keys[i]) { | |
return i; | |
} | |
} | |
return -1; | |
} | |
function searchFor(value) { | |
var i = 0; | |
if (values.indexOf !== undefined) { | |
return values.indexOf(value); | |
} | |
for (i = 0; i < values.length; i += 1) { | |
if (value === values[i]) { | |
return i; | |
} | |
} | |
return -1; | |
} | |
function put(key, value) { | |
var index = indexOf(key); | |
if (index === -1) { | |
keys.push(key); | |
values.push(value); | |
index = indexOf(key); | |
} else { | |
values[index] = value; | |
} | |
return index; | |
} | |
function get(key) { | |
if (typeof key === "number") { | |
return { | |
key: keys[key], | |
value: values[key] | |
}; | |
} | |
var index = indexOf(key); | |
return values[index]; | |
} | |
function remove(key) { | |
var index = indexOf(key); | |
if (index > -1) { | |
keys.splice(index, 1); | |
values.splice(index, 1); | |
return true; | |
} | |
return false; | |
} | |
return { | |
get: get, | |
remove: remove, | |
put: put, | |
indexOf: indexOf, | |
searchFor: searchFor | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment