Created
August 23, 2011 16:45
-
-
Save WebReflection/1165811 to your computer and use it in GitHub Desktop.
how to track old libraries / namespaces
This file contains 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 track(object) { | |
// how to track old libraries, by Andrea Giammarchi | |
// var report = track(genericObject); | |
// ... run whatever you run usually ... | |
// console.log(report); | |
function createGetterSetterIfNecessary(key) { | |
return hasOwnProperty.call(result, key = key.slice(1)) ? | |
result[key] | |
: | |
result[key] = {get:0, set:0} | |
; | |
} | |
function createWrapperIfNecessary(key) { | |
return hasOwnProperty.call(result, key = key.slice(1)) ? | |
result[key] | |
: | |
result[key] = [] | |
; | |
} | |
function fn(fn, key) { | |
function wrap() { | |
var | |
result = fn.apply(this, arguments), | |
instanceCreated = this instanceof wrap, | |
instanceUsed = !result || typeof result != "object" || result === this | |
; | |
createWrapperIfNecessary(key).push({ | |
instanceCreated: this instanceof wrap, | |
instanceUsed: instanceCreated && instanceUsed, | |
arguments: arguments, | |
result: result | |
}); | |
return instanceUsed ? this : result; | |
} | |
wrap.prototype = fn.prototype; | |
return wrap; | |
} | |
function getSet(value, key, method) { | |
return function get() { | |
createGetterSetterIfNecessary(key)[method]++; | |
return value; | |
}; | |
} | |
function overload(object, nmsp) { | |
var key, value, id; | |
for (key in object) { | |
if (hasOwnProperty.call(object, key)) { | |
value = object[key]; | |
id = nmsp + "." + key; | |
if (typeof value == "function") { | |
defineProperty(object, key, { | |
writable: false, | |
configurable: false, | |
enumerable: true, | |
value: fn(value, id) | |
}); | |
} else { | |
if (value && typeof value == "object") { | |
overload(value, id); | |
} | |
defineProperty(object, key, { | |
configurable: false, | |
enumerable: true, | |
get: getSet(value, id, "get"), | |
set: getSet(value, id, "set") | |
}); | |
} | |
} | |
} | |
} | |
var | |
result = {}, | |
defineProperty = Object.defineProperty, | |
hasOwnProperty = result.hasOwnProperty, | |
global = function(){return this}() | |
; | |
overload(object, ""); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment