Skip to content

Instantly share code, notes, and snippets.

@Gozala
Created October 7, 2011 10:34
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save Gozala/1269991 to your computer and use it in GitHub Desktop.
Save Gozala/1269991 to your computer and use it in GitHub Desktop.
Harmony WeakMap shim for ES5
/* vim:set ts=2 sw=2 sts=2 expandtab */
/*jshint asi: true undef: true es5: true node: true devel: true
forin: false latedef: false */
/*global define: true */
if (typeof(WeakMap) === 'undefined') WeakMap = (function(global) {
"use strict";
function defineNamespace(object, namespace) {
/**
Utility function takes `object` and `namespace` and overrides `valueOf`
method of `object`, so that when called with a `namespace` argument,
`private` object associated with this `namespace` is returned. If argument
is different, `valueOf` falls back to original `valueOf` property.
**/
// Private inherits from `object`, so that `this.foo` will refer to the
// `object.foo`. Also, original `valueOf` is saved in order to be able to
// delegate to it when necessary.
var privates = Object.create(object), base = object.valueOf
Object.defineProperty(object, 'valueOf', { value: function valueOf(value) {
// If `this` or `namespace` is not associated with a `privates` being
// stored we fallback to original `valueOf`, otherwise we return privates.
return value != namespace || this != object ? base.apply(this, arguments)
: privates
}, configurable: true })
return privates
}
function Name() {
/**
Desugared implementation of private names proposal. API is different as
it's not possible to implement API proposed for harmony with in ES5. In
terms of provided functionality it supposed to be same.
http://wiki.ecmascript.org/doku.php?id=strawman:private_names
**/
var namespace = {}
return function name(object) {
var privates = object.valueOf(namespace)
return privates !== object ? privates : defineNamespace(object, namespace)
}
}
function guard(key) {
/**
Utility function to guard WeakMap methods from keys that are not
a non-null objects.
**/
if (key !== Object(key)) throw TypeError("value is not a non-null object")
return key
}
function WeakMap() {
/**
Implementation of harmony `WeakMaps`, in ES5. This implementation will
work only with keys that have configurable `valueOf` property (which is
a default for all non-frozen objects).
http://wiki.ecmascript.org/doku.php?id=harmony:weak_maps
**/
var privates = Name()
return Object.freeze(Object.create(WeakMap.prototype, {
has: {
value: function has(object) {
return 'value' in privates(object)
},
configurable: true,
enumerable: false,
writable: true
},
get: {
value: function get(key, fallback) {
return privates(guard(key)).value || fallback
},
configurable: true,
enumerable: false,
writable: true
},
set: {
value: function set(key, value) {
privates(guard(key)).value = value
},
configurable: true,
enumerable: false,
writable: true
},
'delete': {
value: function set(key) {
return delete privates(guard(key)).value
},
configurable: true,
enumerable: false,
writable: true
}
}))
}
return global.WeakMap = WeakMap
})(this)
Copy link

ghost commented May 11, 2012

WeakMaps (and this shim which upholds the spec in all material ways) has three use cases that I find a lot of use for:

1.) Wrapping/unwrapping public/private values. A regular map also serves here but the implementation of the shim is the same for a map as it is for a weak map.

2.) Extension of 1 is mapping an object to a private data store for it. This is providing the same service as, for example, jQuery.data to attach data to DOM elements without causing memory leaks. Except jQuery's method (same one used by every library I know) only protects from one end. All the JS values in the data store will never be garbage collected. Using this shim (and regular WeakMaps of course) you can provide a way for JS objects to be garbage collected with the DOM elements they are backing.

3.) Secure public/private unforgeable data transmission. This shim is just as secure real WeakMaps and there's a lot of coll things you can do with them (outlined on the Wiki).

I expanded the idea backing the shim in this gist into a pretty complete implementation https://github.com/Benvie/ES6-Harmony-Collections-Shim (replacing my older much worse repo by the same name). It incorporates some ideas from the SES implementation into this one, and expands on both.

First, a unique randomly generated namespace is created upon first shimming. This doesn't need to be secure, just something that won't accidentally conflict with normal usage of objects. At the same time, Object.getOwnPropertyNames is patched. This is a very light patch that is pretty efficient. It basically checks for hasOwn(obj, randomNamespace) and splices it if it exists. With GOPN patched and using a non-enumerable property the shim becomes almost entirely non-observable. In order to observe it you'd have to grab a new GOPN from another context or have a reference to the original one.

Inside this single random namspace per session is where the data is stored. Each WeakMap instance also generates a random name which it uses to store the Name on. This way there's no issue with conflicts or having to wrap the same unlocker in multiple layers, and you also don't litter objects with a bunch of random keys. Just the one single common name that houses the rest.

Then using the initial WeakMap shim I bootstrap in Map and Set (also Hashmap which is paired with WeakMap to implement primitive keys). The collection instances themselves are stored using the private storage, so the interfaces provided are almost identical to the real implementation (prototype methods instead of per instance bound versions).

@allenwb
Copy link

allenwb commented May 11, 2012

@Benvie Sorry, like SimonGianni pointed out. This does not have the GC behavior that is required for WeakMap. It may well be functionally a fine shim for the map functionality of WeakMap but it will be leaky. It is impossible to emulate the required GC behavior outside of the garbage collector. That's why WeakMap exists.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment