Last active
September 1, 2020 21:55
-
-
Save petsel/3b31cd5e63d43b9e7c4e to your computer and use it in GitHub Desktop.
possible implementation of prototypal method modifier [afterFinally].
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 (Function) { | |
const fctPrototype = Function.prototype; | |
const FUNCTION_TYPE = (typeof Function); | |
function isFunction(type) { | |
return ( | |
(typeof type == FUNCTION_TYPE) | |
&& (typeof type.call == FUNCTION_TYPE) | |
&& (typeof type.apply == FUNCTION_TYPE) | |
); | |
} | |
function getSanitizedTarget(target) { | |
/* eslint-disable */ | |
/* jshint ignore:start */ | |
/* ignore jslint start */ | |
/* no-eq-null */ | |
return ((target != null) && target) || null; | |
/* ignore jslint end */ | |
/* jshint ignore:end */ | |
/* eslint-enable */ | |
} | |
function afterFinally/*Modifier*/(handler, target) { | |
target = getSanitizedTarget(target); | |
const proceed = this; | |
return ( | |
isFunction(handler) && | |
isFunction(proceed) && | |
function () { | |
const context = target || getSanitizedTarget(this); | |
const args = arguments; | |
let result, error; | |
try { | |
result = proceed.apply(context, args); | |
} catch (exception) { | |
error = exception; | |
} // finally { ... } | |
result = (error || result); | |
handler.call(context, result, args); | |
return result; | |
} | |
) || proceed; | |
} | |
// afterFinally.toString = () => 'afterFinally() { [native code] }'; | |
Object.defineProperty(fctPrototype, 'afterFinally', { | |
configurable: true, | |
writable: true, | |
value: afterFinally/*Modifier*/ | |
}); | |
// provide static implementation as well. | |
function staticAfterFinally/*Modifier*/(proceed, handler, target) { | |
return afterFinally.call(proceed, handler, target); | |
} | |
// staticAfterFinally.toString = () => 'afterFinally() { [native code] }'; | |
// staticAfterFinally.toString = () => 'staticAfterFinally() { [native code] }'; | |
Object.defineProperty(Function, 'afterFinally', { | |
configurable: true, | |
writable: true, | |
value: staticAfterFinally/*Modifier*/ | |
}); | |
}(Function)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment