ES6-Map

// 原理: 链表、hash算法、桶
// 桶: 在桶内拟定8个空间, 链表: next, hash算法: 把不定的值变为特定范围的值 [0, 8)
// 用数组拟定为桶,桶内8个空间
// 传入的值可能为 object,array,string,number,undefined,NaN,boolean…
// 将传入的值通过hash算法求出[0, 8)的特定值,最后通过链表插入
// 1.不重复
// 2.字符串 数值 NaN null [] {} function(){}…
// 3.set get delete has clear
function Map () {
	this.bucketLen = 8;
	this.init();
}
Map.prototype.init = function () {
	this.bucket = new Array(this.bucketLen);
	for(var i = 0; i < this.bucketLen; i++){
		this.bucket[i] = {
			type: 'bucken_' + i,
			next: null
		}
	}
}
Map.prototype.hash = function (key) {
	var hash = 0;
	if(typeof key != 'string'){
		if(typeof key == 'number'){
			hash = Object.is(key, NaN) ? 0 : key;
		}else if(typeof key == 'object'){
			hash = 1;
		}else if(typeof key == 'boolean'){
			hash = +key;
		}else{
			hash = 2;
		}
	}else{
		for(var i = 0; i < 3; i++){
			hash += key[i] ? key.charCodeAt(i) : 0;
		}
	}
	return hash % 8;
}
Map.prototype.set = function (key, val) {
	var hash = this.hash(key);
	var oTempBucket = this.bucket[hash];
	while(oTempBucket.next){
		if(oTempBucket.next.key){
			oTempBucket.next.key = val;
		}else{
			oTempBucket = oTempBucket.next;
		}
	}
	oTempBucket.next = {
		key: key,
		val: val,
		next: null
	}
}
Map.prototype.get = function (key) {
	var hash = this.hash(key);
	var oTempBucket = this.bucket[hash];
	while(oTempBucket.next){
		if(oTempBucket.next.key == key){
			return oTempBucket.next.val;
		}else{
			oTempBucket = oTempBucket.next;
		}
	}
	return undefined;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值