//实现hasnArrayMap
var
hashMap =
function
(){
this
.items = [];
this
.map = {};
}
hashMap.prototype.set =
function
(key,value){
var
isFindInArray =
false
;
var
obj ={key:key, value:value};
for
(
var
i = 0;i<
this
.items.length;i++){
if
(
this
.items[i].key == key) {
obj.index = i;
this
.items[i] = obj;
isFindInArray =
true
;
break
;
}
}
if
(!isFindInArray) {
this
.items.push(obj);
obj.index =
this
.items.length - 1;
}
this
.map[key] = value;
}
hashMap.prototype.get =
function
(){
var
isKey =
typeof
(arguments[0]) ===
'string'
;
if
(isKey) {
return
this
.map[arguments[0]];
}
else
{
if
(
typeof
(arguments[0])==
'number'
) {
var
index = parseInt(arguments[0]);
if
(index >= 0 && index <
this
.items.length) {
return
this
.items[index].value;
}
else
{
return
'undefined'
;
}
}
else
{
return
'undefined'
;
}
}
}
hashMap.prototype.remove =
function
(){
var
isKey =
typeof
(arguments[0]) ===
'string'
;
if
(isKey) {
return
this
._remove(
this
.map[arguments[0]]);
}
else
{
if
(
typeof
(arguments[0])==
'number'
) {
var
index = parseInt(arguments[0]);
if
(index >= 0 && index <
this
.items.length) {
return
this
._remove(
this
.items[index]);
}
else
{
return
'array over flow'
;
}
}
else
{
return
'wrong arguments'
;
}
}
}
hashMap.prototype._remove =
function
(obj){
if
(obj) {
var
index = obj.index,
key = obj.key;
this
.items.splice(index ,1);
if
(
this
.map[key])
delete
this
.map[key];
}
return
true
;
}
hashMap.prototype.size =
function
(){
return
this
.items.length;
}
/*
var testArray = new SixDegree.hashMap();
testArray.set('name1' , '1');
testArray.set('name2' , '2');
testArray.set('name3' , '3');
console.log(testArray.get('name1'));
console.log(testArray.get('name2'));
console.log(testArray.get('name3'));
console.log(testArray.get(0));
console.log(testArray.get(1));
console.log(testArray.get(2));
testArray.remove(0);
for(var i=0 , len = testArray.size();i<len ; i++){
console.log(testArray.get(i));
}
testArray.remove('name2');
for(var i=0 , len = testArray.size();i<len ; i++){
console.log(testArray.get(i));
}
*/