Skip to content

Instantly share code, notes, and snippets.

@hbakhtiyor
Created June 30, 2015 10:39
Show Gist options
  • Save hbakhtiyor/bfebc2e541349dc7c1e3 to your computer and use it in GitHub Desktop.
Save hbakhtiyor/bfebc2e541349dc7c1e3 to your computer and use it in GitHub Desktop.
Restricting some methods for resolving challenges without using the methods
// Method names for exclusion
excludes = []
// e.g. excluding pop & push methods
// excludes = ['pop', 'push'];
// Objects for mocking
objects = [Array];
// The restriction only effect inside the
// function (nested functions, chained invoking functions, ...)
var fnName = 'solution';
// Finding called function from stack
var calledFromThatFunction = function(caller) {
while(caller) {
if(caller.name === fnName)
return true;
caller = caller.caller;
}
return false;
};
objects.forEach(function(object) {
// Fetching all Object's property and filtering with exclude methods
Object.getOwnPropertyNames(object).filter(function(methodName) {
return excludes.indexOf(methodName) === -1;
}).forEach(function(black) {
if(typeof object[black] === 'function') {
var _proto = object.prototype;
// Randomize the method name
var newName = '__' + Math.random().toString(36).slice(4) + black + '__';
// Holding old reference of the method
_proto[newName] = _proto[black];
object[newName] = object[black];
// Mocking the current method
_proto[black] = function() {
if(calledFromThatFunction(_proto[black].caller))
console.log('.' + black + '() is prohibited.');
else
return _proto[newName].apply(_proto[newName], arguments);
};
// Mocking also Object generic methods
object[black] = function() {
if(calledFromThatFunction(object[black].caller))
console.log('.' + black + '() is prohibited.');
else
return object[newName].apply(object[newName], arguments);
};
}
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment