Skip to content

Instantly share code, notes, and snippets.

@TooTallNate
Created September 23, 2011 22:08
Show Gist options
  • Save TooTallNate/1238561 to your computer and use it in GitHub Desktop.
Save TooTallNate/1238561 to your computer and use it in GitHub Desktop.
Creating a barebones WeakMap with node-weak (String keys only)
var weak = require('weak')
// This is our weakmap; a regular JS Object
var map = {}
// This is the object we wanna store a weak reference to
var anObj = { foo: 'bar' }
, key = 'anObj'
// Create a weak reference and store it in the map.
// Arguments:
// 1) the object to create a reference to
// 2) the callback function to call when being GC'd
// 3,4,...) Any arguments that should be given to the callback function when invoked
map[key] = weak(anObj, cleanup, key)
// function that gets called when the weak reference is being GC'd
// in this case, remove the dead weak ref from the weakmap
function cleanup (key) {
delete map[key]
}
// Now destory the only *strong* reference to anObj
anObj = null
// Now we can retrieve the object from the weak map
weak.get(map[key])
Object.keys(map).length // 1
// Run the GC (with --expose-gc)
gc()
// and after the GC runs, anObj will no longer be in the weakmap
Object.keys(map).length // 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment