locutus
Version:
Locutus other languages' standard libraries to JavaScript for fun and educational purposes
43 lines (42 loc) • 1.75 kB
JavaScript
import { getPhpGlobalEntry, getPhpObjectEntry } from "./_phpRuntimeState.js";
import { isObjectLike, isPhpCallable, } from "./_phpTypes.js";
export function resolvePhpCallable(callback, options) {
if (isPhpCallable(callback)) {
return { fn: callback, scope: null };
}
if (typeof callback === 'string') {
const candidate = getPhpGlobalEntry(callback);
if (isPhpCallable(candidate)) {
return { fn: candidate, scope: null };
}
throw new Error(options.invalidMessage);
}
if (Array.isArray(callback) && callback.length >= 2) {
const scopeDescriptor = callback[0];
const callableDescriptor = callback[1];
let scope;
if (typeof scopeDescriptor === 'string') {
scope = getPhpGlobalEntry(scopeDescriptor);
if (typeof scope === 'undefined' && options.missingScopeMessage) {
throw new Error(options.missingScopeMessage(scopeDescriptor));
}
}
else {
scope = scopeDescriptor;
}
if (isPhpCallable(callableDescriptor)) {
return { fn: callableDescriptor, scope };
}
if (typeof callableDescriptor === 'string' && (isObjectLike(scope) || typeof scope === 'function')) {
const candidate = getPhpObjectEntry(scope, callableDescriptor);
if (isPhpCallable(candidate)) {
return { fn: candidate, scope };
}
}
}
throw new Error(options.invalidMessage);
}
export function resolveNumericComparator(callback, invalidMessage) {
const resolved = resolvePhpCallable(callback, { invalidMessage });
return (left, right) => Number(resolved.fn.apply(resolved.scope, [left, right]));
}