Skip to content

Instantly share code, notes, and snippets.

@Gaubee
Created October 29, 2017 02:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Gaubee/91b34fc56f3890bdbad681d4a8f47424 to your computer and use it in GitHub Desktop.
Save Gaubee/91b34fc56f3890bdbad681d4a8f47424 to your computer and use it in GitHub Desktop.
JS实现+=/-=操作符号的重载
// __op_temp_null_: 说明缓存取中没有东西
Object.defineProperty(global, "__op_temp_null_", {
value: Symbol("Operators Object NULL")
});
const op_temp_key = Symbol("Operators Object TEMP");
Object.defineProperty(global, "__op_temp__", {
get() {
const res = this[op_temp_key];
// 取值后马上移除引用关系
this[op_temp_key] = global.__op_temp_null_;
return res;
},
set(v) {
this[op_temp_key] = v;
}
});
class PromisePool extends Array {
constructor(...args) {
super(...args);
// 使用小数来作为ID标识
Object.defineProperty(this, "_base", {
value: 0.4572015816549748
});
// -= 的时候使用
Object.defineProperty(this, "_base_res", {
value: 1 - this._base
});
}
get pool() {
return this._base;
}
set pool(v) {
var cv = "0." + v.toString().split(".")[1];
// 从缓存取获取对象
const obj = global.__op_temp__;
if (obj === global.__op_temp_null_) {
console.error("NO THING IN TEMP");
return;
}
if(!(obj instanceof Promise)){
console.error("MUST Be Promise Instance");
return;
}
// console.log(obj)
if (cv == this._base) {
// 使用了+=运算符
this.push(obj);
} else if (cv == this._base_res) {
// 使用了-=运算符
var index = this.indexOf(obj);
if (index >= 0) {
this.splice(index, 1);
}
} else {
// 忽略,或者抛出异常
console.error(cv, this._base);
}
}
}
pp = new PromisePool();
Object.defineProperty(Promise, "__OP_VAL__", { value: 0 });
Promise.prototype.valueOf = function() {
global.__op_temp__ = this;
return Promise.__OP_VAL__;
};
var pitem = Promise.resolve(666);
pp.pool += pitem;
console.log(pp.length, pp[0]);
console.log("-------------");
pp.pool += 0;
console.log(pp.length, pp[0]);
console.log("-------------");
pp.pool -= pitem;
console.log(pp.length, pp[0]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment