Skip to content

Instantly share code, notes, and snippets.

@petsel
Created September 4, 2024 09:04
Show Gist options
  • Save petsel/7f7e5b56f2bde78698474d0ad0b1fd4f to your computer and use it in GitHub Desktop.
Save petsel/7f7e5b56f2bde78698474d0ad0b1fd4f to your computer and use it in GitHub Desktop.
function exposeInternalType(value) {
return Object.prototype.toString.call(value);
}
function isAsyncFuntionType(value) {
return exposeInternalType(value) === '[object AsyncFunction]';
}
function isFunction(value) {
return (
typeof value === 'function' &&
typeof value.call === 'function' &&
typeof value.apply === 'function'
);
}
function execute/*Safely*/(target, ...args) {
const proceed = this;
let result = null;
let error = null;
if (isFunction(proceed)) {
if (isAsyncFuntionType(proceed)) {
error = new TypeError(
'The non-async `execute` exclusively can be invoked at non-async callable types.'
);
} else {
try {
result = proceed.apply(target ?? null, args);
} catch (/** @type {Error} */exception) {
error = exception;
}
}
} else {
error = new TypeError(
'`execute` exclusively can be invoked at a callable type.'
);
}
return [/** @type {null|Error} */error, result];
}
async function executeAsync/*Safely*/(target, ...args) {
const proceed = this;
let result = null;
let reason = null;
let error = null;
if (isFunction(proceed)) {
try {
result = await proceed.apply(target ?? null, args);
} catch (/** @type {string|Error} */exception) {
reason = exception;
}
} else {
error = new TypeError(
'`execute` exclusively can be invoked at a callable type.'
);
}
return [/** @type {null|string|Error} */reason ?? error, result];
}
Reflect.defineProperty(Function.prototype, 'execute', {
value: execute,
writable: true,
configurable: true,
});
Reflect.defineProperty((async function () {}).constructor.prototype, 'execute', {
value: executeAsync,
writable: true,
configurable: true,
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment