【H5开发】在ts中实现一个支持泛型的HashSet类(下集):案例源代码!

版权声明:本文为博主原创文章,如需转载请注明出处,谢谢。喜欢请关注哟~ https://blog.csdn.net/sjt223857130/article/details/80376956

上一节,我们用typescript语言实现了一个支持泛型的HashMap类,

这一节,我们要实现HashSet起来,就太容易了。


话不多说,直接上码!!


HashSet.ts

namespace sunnyboxs
{

export class HashSet< T> {

private items: { [ key: string]: T; };

constructor()
{
this. items = {};
}

public add( key: string, value: T): void
{
this. items[ key] = value;
}

public del( key: string): boolean
{
return delete this. items[ key];
}

public has( key: string): boolean
{
return key in this. items;
}

public get( key: string): T
{
return this. items[ key];
}

public length(): number
{
return Object. keys( this. items). length;
}

public forEach( f: { ( key: string, val: any): void })
{
for ( let k in this. items)
{
f( k, this. items[ k]);
}
}
}
}



测试应用代码如下:


var m: HashSet< string> = new HashSet< string>();
m. add( "key1", "val1");
m. add( "key2", "val2");
m. add( "key3", "val3");
console. log( m);
// 遍历方法
m. forEach( function ( k, v)
{
console. log( k + ":" + v);
});



在浏览器中输出调试结果:

HashSet
key1:val1
key2:val2
key3:val3


     OK!大功告成!!!   



猜你喜欢

转载自blog.csdn.net/sjt223857130/article/details/80376956