Skip to content

Instantly share code, notes, and snippets.

@Raynos
Forked from Gozala/weak-map.js
Last active September 18, 2019 07:49
Show Gist options
  • Select an option

  • Save Raynos/1638059 to your computer and use it in GitHub Desktop.

Select an option

Save Raynos/1638059 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
}})
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
}
}
}))
}
return global.WeakMap = WeakMap
})(this)
@Krinkle
Copy link

Krinkle commented Oct 10, 2012

        get: function (key, fallback) {
            return privates(key).value || fallback
        }

This fails in case of false-y values. As documented values can be anything, including (but not limited to) objects, functionss, and undefined.

var foo = {};
wm.set(foo, false);
wm.set(foo, null);
wm.set(foo, undefined);
wm.set(foo, 0);
wm.set(foo, '');

// For all of these, the below returns the default value instead of the stored value:
wm.get(foo, 'default for unset properties');

Fix:

        get: function (key, fallback) {
            var store = privates(key);
            return store.hasOwnProperty('value') ? store.value : fallback;
        }

@FritsvanCampen
Copy link

There is a (minor) bug in this implementation. It is possible to craft a value that will return a value for wm.get even though it's not in the WeakMap. A value that looks like this:

crafted_value = {
    "valueOf": function () {
        return { "value": "some value" };
    }
};

wm.get(crafted_value, "some other value"); will return "some value" instead.

You can fix this in many different ways but they all boil down to the same thing: the value that you get from the store must be associated with the identity of the WeakMap.

My solution:

Construct your store like this: (line 21)

var store = {
    identity: key
}

And check like this: (line 38)

return store && store.identity === key ? store : namespace(obj, key)

You need the truethy check on store to avoid bugs with 'strange' implementations of valueOf that return undefined. store !== undefined also works and might be better.

@Raynos
Copy link
Author

Raynos commented Mar 24, 2014

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