ts-flex-query
Version:
Flexible and type-safe data queries
52 lines • 1.93 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.nameOf = exports.expectType = void 0;
exports.createObjectFromArray = createObjectFromArray;
exports.createObjectFromObject = createObjectFromObject;
exports.typePredicate = typePredicate;
exports.unexpected = unexpected;
exports.isDefined = isDefined;
exports.assertIsDefined = assertIsDefined;
/** Creates an object from an array. */
function createObjectFromArray(array, keyGetter, valueGetter) {
return array.reduce((acc, element) => {
acc[keyGetter(element)] = valueGetter ? valueGetter(element) : element;
return acc;
}, {});
}
/** Creates a new object from the given object by rewriting keys and values. */
function createObjectFromObject(obj, valueGetter, keyGetter) {
return createObjectFromArray(Object.entries(obj), (entry) => { var _a; return (_a = keyGetter === null || keyGetter === void 0 ? void 0 : keyGetter(entry[0])) !== null && _a !== void 0 ? _a : entry[0]; }, (entry) => valueGetter(entry[1], entry[0]));
}
/** Produces a test function to check if a value is of a given type. */
function typePredicate(f) {
return f;
}
/**
* Throws an error when called.
* Used to mark code that must not be executed.
*/
function unexpected(x) {
throw new Error('Unexpected value: ' + x);
}
/**
* Creates a type expector method.
* Its first argument is the value to test.
* The second argument must be true.
* The assertion fails if one of T and U is "any" but not both or if U does not extend T.
*/
const expectType = () => () => {
// Nothing to do.
};
exports.expectType = expectType;
const nameOf = () => (field) => field;
exports.nameOf = nameOf;
function isDefined(value) {
return value !== undefined && value !== null;
}
function assertIsDefined(value, errorMessage) {
if (!isDefined(value)) {
throw new Error(errorMessage);
}
}
//# sourceMappingURL=utils.js.map