Skip to content

Instantly share code, notes, and snippets.

@petsel
Last active September 1, 2020 21:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petsel/3b31cd5e63d43b9e7c4e to your computer and use it in GitHub Desktop.
Save petsel/3b31cd5e63d43b9e7c4e to your computer and use it in GitHub Desktop.
possible implementation of prototypal method modifier [afterFinally].
(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