Skip to content

Commit

Permalink
initial
Browse files Browse the repository at this point in the history
  • Loading branch information
Brandon Benvie committed Sep 30, 2012
0 parents commit e7a75ad
Show file tree
Hide file tree
Showing 3 changed files with 309 additions and 0 deletions.
94 changes: 94 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
# WeakMap Shim
This is a standalone shim for WeakMap, separated out from the full Harmony Collections shim at https://github.com/Benvie/harmony-collections. WeakMap is by far the most useful new addition. If you only need to use objects as keys then uou can use this much more compact library that doesn't have to implement three other classes.

## Compatability

Works with IE9+, Chrome, Firefox, Safari, untested in Opera.

## Install/Use

If using node, install via:

npm install weakmap

In the browser, include __weakmap.js__ or ____weakmap.min.js__ and WeakMap will be exposed on the window.

## Overview

WeakMaps provide a new core weapon to your JS arsenal: objects as keys. This allows you to do the following awesome things: store private data "on" public objects, private properties, secretly "tag" objects, namespace properties, access controlled properties, check object uniqueness in `O(1)` time complexity.

### WeakMap Garbage Collection Semantics

A benefit of using WeakMaps is enhanced garbage collection. In a WeakMap, the only reference created is key -> value, so it's possible for a key/value in a WeakMap to be garbage collected while the WeakMap they're in still exists! Compare this to an Array, where all items in the Array will not be garbage collected as long as the Array isn't. This forces either explicit management of object lifespans or, more commonly, simply results in memory leaks.

For example, data stored using jQuery.data can never be garbage collected unless explicitly nulled out, because it is stored in a container that strongly references the items held inside. Using a WeakMap, it's possible to associate data with an element and have the data destroyed when the element is -- without memory leaking the element; i.e. `weakmap.set(element, { myData: 'gc safe!' })`. jQuery.data (every library has similar functionality) prevents the *element* from memory leaking by using a numeric id, but this does nothing for the __data__ that is stored.

## Example

```javascript
// reusable storage creator
function createStorage(){
var store = new WeakMap;
return function(o){
var v = store.get(o);
if (!v) store.set(o, v = {});
return v;
};
}

// allows private/namespaced properties for the objects
var _ = createStorage();

functioon Wrapper(element){
var _element = _(element);
if (_element.wrapper)
return _element.wrapper;

_element.wrapper = this;
_(this).element = element;
}

Wrapper.prototype = {
get classes(){
return [].slice.call(_(this).element.classList);
},
set classes(v){
_(this).element.className = [].concat(v).join(' ');
}
};
```


## API Reference

* WeakMaps may be inherited from. Initialize objects via `WeakMap.call(obj)`.

### WeakMap

__Non-primitives__ are valid keys. Objects, functions, DOM nodes, etc.

WeakMaps require the use of objects as keys; primitives are not valid keys. WeakMaps have no way to enumerate their keys or values. Because of this, the only way to retrieve a value from a WeakMap is to have access to both the WeakMap itself as well as an object used as a key.

* `new WeakMap(iterable)` Create a new WeakMap populated with the iterable. Accepts *[[Key, Value]...]*, *Array*, *Iterable*.
* `WeakMap#set(key, value)` Key must be non-primitive. Returns undefined.
* `WeakMap#get(key)` Returns the value that key corresponds to the key or undefined.
* `WeakMap#has(key)` Returns boolean.
* `WeakMap#delete(key)` Removes the value from the collection and returns boolean indicating if there was a value to delete.


## License

(The MIT License)
Copyright (c) 2012 Brandon Benvie <http://bbenvie.com>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
(the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included with all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14 changes: 14 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"author": "Brandon Benvie <http://bbenvie.com>",
"name": "weakmap",
"description": "Shim for WeakMap with non-leaky O(1) lookup time",
"keywords": ["harmony", "collection", "weakmap","ecmascript", "es6", "shim", "garbage collection", "gc"],
"version": "0.0.1",
"homepage": "http://benvie.github.com/WeakMap",
"repository": {
"type": "git",
"url": "https://github.com/Benvie/WeakMap"
},
"main": "WeakMap.js",
"license": "MIT"
}
201 changes: 201 additions & 0 deletions weakmap.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,201 @@
/* (The MIT License)
*
* Copyright (c) 2012 Brandon Benvie <http://bbenvie.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the 'Software'), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included with all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

// Original WeakMap implementation by Gozala @ https://gist.github.com/1269991
// Updated and bugfixed by Raynos @ https://gist.github.com/1638059
// Expanded by Benvie @ https://github.com/Benvie/harmony-collections

void function(global, undefined_, undefined){
"use strict";

var getProps = Object.getOwnPropertyNames,
defProp = Object.defineProperty,
toSource = Function.prototype.toString,
create = Object.create,
hasOwn = Object.prototype.hasOwnProperty,
funcName = /^\n?function\s?(\w*)?_?\(/;


function define(object, key, value){
if (typeof key === 'function') {
value = key;
key = nameOf(value).replace(/_$/, '');
}
return defProp(object, key, { configurable: true, writable: true, value: value });
}

function nameOf(func){
return typeof func !== 'function'
? '' : 'name' in func
? func.name : toSource.call(func).match(funcName)[1];
}

// ############
// ### Data ###
// ############

var Data = (function(){
var dataDesc = { value: { writable: true, value: undefined } },
datalock = 'return function(k){if(k===s)return l}',
uids = create(null),
globalID = createUID();

function createUID(){
var key = Math.random().toString(36).slice(2);
return key in uids ? createUID() : uids[key] = key;
}

function storage(obj){
if (hasOwn.call(obj, globalID))
return obj[globalID];

if (!Object.isExtensible(obj))
throw new TypeError("Object must be extensible");

var store = create(null);
defProp(obj, globalID, { value: store });
return store;
}

// common per-object storage area made visible by patching getOwnPropertyNames'
define(Object, function getOwnPropertyNames(obj){
var props = getProps(obj);
if (hasOwn.call(obj, globalID))
props.splice(props.indexOf(globalID), 1);
return props;
});

function Data(){
var puid = createUID(),
secret = {};

this.unlock = function(obj){
var store = storage(obj);
if (hasOwn.call(store, puid))
return store[puid](secret);

var data = create(null, dataDesc);
defProp(store, puid, {
value: new Function('s', 'l', datalock)(secret, data)
});
return data;
}
}

define(Data.prototype, function get(o){ return this.unlock(o).value });
define(Data.prototype, function set(o, v){ this.unlock(o).value = v });

return Data;
}());


var WeakMap = (function(data){
function validate(key){
if (key == null || typeof key !== 'object' && typeof key !== 'function')
throw new TypeError("Invalid WeakMap key");
}

function wrap(collection, value){
var store = data.unlock(collection);
if (store.value)
throw new TypeError("Object is already a WeakMap");
store.value = value;
}

function unwrap(collection){
var storage = data.unlock(collection).value;
if (!storage)
throw new TypeError("WeakMap is not generic");
return storage;
}

function initialize(weakmap, iterable){
if (iterable !== null && typeof iterable === 'object' && typeof iterable.forEach === 'function') {
iterable.forEach(function(item, i){
if (item instanceof Array && item.length === 2)
set.call(weakmap, iterable[i][0], iterable[i][1]);
});
}
}


function WeakMap(iterable){
if (this === global || this == null || this === prototype)
return new WeakMap(iterable);

wrap(this, new Data);
initialize(this, iterable);
}

function get(key){
validate(key);
var value = unwrap(this).get(key);
return value === undefined_ ? undefined : value;
}

function set(key, value){
validate(key);
// store a token for explicit undefined so that "has" works correctly
unwrap(this).set(key, value === undefined ? undefined_ : value);
}

function has(key){
validate(key);
return unwrap(this).get(key) !== undefined;
}

function delete_(key){
validate(key);
var data = unwrap(this),
had = data.get(key) !== undefined;
data.set(key, undefined);
return had;
}

function toString(){
unwrap(this);
return '[object WeakMap]';
}

try {
var src = ('return '+delete_).replace('e_', '\\u0065');
var del = new Function('unwrap', 'validate', src)(unwrap, validate);
} catch (e) {
var del = delete_;
}

var src = (''+Object).split('Object');
[toString, get, set, has, del].forEach(function(method){
define(WeakMap.prototype, method);
define(method, function toString(){
return src[0] + nameOf(this) + src[1];
});
});

return WeakMap;
}(new Data));

if (typeof module !== 'undefined')
module.exports = WeakMap;
else if (typeof exports !== 'undefined')
exports.WeakMap = WeakMap;
else if (!('WeakMap' in global)
global.WeakMap = WeakMap;
}(new Function('return this')(), {});

0 comments on commit e7a75ad

Please sign in to comment.