shelving
Version:
Toolkit for using data in JavaScript.
19 lines (18 loc) • 875 B
JavaScript
import { RequiredError } from "../error/RequiredError.js";
import { isObject } from "./object.js";
/** Recurse through `Sourceable` objects and return the first one that is an instance of `type`, or `undefined` if no source object matches. */
export function getSource(type, value) {
if (isObject(value)) {
if (value instanceof type)
return value;
if ("source" in value)
return getSource(type, value.source);
}
}
/** Recurse through `Sourceable` objects and return the first one that is an instance of `type`, or throw `RequiredError` if no source object matches. */
export function requireSource(type, data, caller = requireSource) {
const source = getSource(type, data);
if (!source)
throw new RequiredError(`Source "${type.name}" not found`, { received: data, expected: type, caller });
return source;
}