代码:
/**
* name
*/
module utils{
/**
* 这是一个key只能是基础结构的Map.
*/
export class HashMap {
private _keyobj:Object={};
private _keyDic:laya.utils.Dictionary=new laya.utils.Dictionary();
private _valueArr:Array<any>=[];
constructor(){
}
public initObj():void
{
}
public destroyObj():void
{
this._keyDic.clear();
this._keyobj={};
this._valueArr.length=0;
}
/**
* 根据索引获取值
*/
public getValueByIndex(index:number):any
{
if(this._valueArr.length<=index)
{
return null;
}
return this._valueArr[index];
}
/**
* 长度
*/
public get length():number
{
return this._valueArr.length+this._keyDic.keys.length;
}
/**
* 获取key,value的表达形式
* @param includeDic 是否包含字典内容,也就是key是复杂的对象,是存储在字典中的,只有为true才可以读取到。
* @param 传入的includeDic为true则返回Dictionary,否则返回Object;
*/
public getValueObjs(includeDic:boolean=false):any
{
if(includeDic==false)
{
return this._keyobj;
}
var newObj:laya.utils.Dictionary=new laya.utils.Dictionary();
var arr:Array<any>=this._keyDic.keys;
if(arr&&arr.length>0)
{
for(var i:number=0;i<arr.length;i++)
{
newObj.set(arr[i],this._keyDic.get(arr[i]));
}
}
var key:any;
for(key in this._keyobj)
{
newObj.set(key,this._keyobj[key]);
}
return newObj;
}
/**
* 获取值。不要对数组做处理,因为返回的是原始数据。
* @parma includeDic 是否包含字典内容,也就是key是复杂的对象,是存储在字典中的,只有为true才可以读取到。
*/
public getValues(includeDic:boolean=false):Array<any>
{
if(includeDic==false)
{
return this._valueArr;
}
var reValues:Array<any>;
var dicValues:Array<any>=this._keyDic.values;
if(dicValues&&dicValues.length>0)
{
reValues=this._valueArr.concat(dicValues);
}
else
{
reValues=this._valueArr;
}
return reValues;
}
/**
* 添加
* @param key 索引
* @param value 值
*/
public push(key:any,value:any):void
{
var ty:string=typeof key;
if(ty=="string"||ty=="number"||ty=="boolean")
{
if(this._keyobj[key]==null)
{
this._valueArr.push(value);
}
else
{
if(this._keyobj[key]!=value)
{
//值有变化,则需要删除,在添加。
this.replaceByKey(key,value);
}
}
this._keyobj[key]=value;
}
else
{
this._keyDic.set(key,value);
}
}
/**
* 获取值
*/
public getByKey(key:any):any
{
var ty:string=typeof key;
if(ty=="string"||ty=="number"||ty=="boolean")
{
return this._keyobj[key];
}
else
{
return this._keyDic.get(key);
}
}
/**
* 删除
* key 删除对应的值
*/
public removeByKey(key:any):void
{
var ty:string=typeof key;
if(ty=="string"||ty=="number"||ty=="boolean")
{
var value:any=this._keyobj[key];
if(value!=undefined)
{
for(var i:number=0;i<this._valueArr.length;i++)
{
if(this._valueArr[i]==value)
{
this._valueArr.splice(i,1);
break;
}
}
}
delete this._keyobj[key];
}
else
{
this._keyDic.remove(key);
}
}
/**
* 替换key对应的value
*/
public replaceByKey(key:any,reValue:any):void
{
var ty:string=typeof key;
if(ty=="string"||ty=="number"||ty=="boolean")
{
var value:any=this._keyobj[key];
if(value!=undefined)
{
for(var i:number=0;i<this._valueArr.length;i++)
{
if(this._valueArr[i]==value)
{
// this._valueArr.splice(i,1);
this._valueArr[i]=reValue;
break;
}
}
}
}
else
{
this._keyDic.set(key,reValue);
}
}
}
}
网友评论