Last active
August 29, 2015 13:56
-
-
Save ghoullier/8979713 to your computer and use it in GitHub Desktop.
WeakMap polyfill
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;(function(root) { | |
function WeakMap() { | |
if (!(this instanceof WeakMap)) { | |
throw new TypeError('Illegal invocation') | |
} | |
var indexes = [] | |
, values = [] | |
this.has = _has.bind(this, indexes, values) | |
this.set = _set.bind(this, indexes, values) | |
this.get = _get.bind(this, indexes, values) | |
this['delete'] = _delete.bind(this, indexes, values) | |
this.clear = _clear.bind(this, indexes, values) | |
} | |
function _has(indexes, values, key) { | |
return indexes.indexOf(key) > -1 | |
} | |
function _set(indexes, values, key, value) { | |
var index | |
if (this.has(key)) { | |
index = indexes.indexOf(key) | |
} else { | |
index = indexes.length | |
indexes.push(key); | |
} | |
values[index] = value | |
} | |
function _get(indexes, values, key, defaultValue) { | |
return this.has(key) ? values[indexes.indexOf(key)] : defaultValue | |
} | |
function _delete(indexes, values, key) { | |
if (this.has(key)) { | |
var index = indexes.indexOf(key) | |
indexes.splice(index, 1) | |
values.splice(index, 1) | |
} | |
} | |
function _clear(indexes, values) { | |
indexes.length = 0 | |
values.length = 0 | |
} | |
root.WeakMap = WeakMap | |
}(this)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
!function(a){function b(){if(!(this instanceof b))throw new TypeError("Illegal invocation");var a=[],h=[];this.has=c.bind(this,a,h),this.set=d.bind(this,a,h),this.get=e.bind(this,a,h),this["delete"]=f.bind(this,a,h),this.clear=g.bind(this,a,h)}function c(a,b,c){return a.indexOf(c)>-1}function d(a,b,c,d){var e;this.has(c)?e=a.indexOf(c):(e=a.length,a.push(c)),b[e]=d}function e(a,b,c,d){return this.has(c)?b[a.indexOf(c)]:d}function f(a,b,c){if(this.has(c)){var d=a.indexOf(c);a.splice(d,1),b.splice(d,1)}}function g(a,b){a.length=0,b.length=0}a.WeakMap=b}(this); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment