@signaldb/core
Version:
SignalDB is a client-side database that provides a simple MongoDB-like interface to the data with first-class typescript support to achieve an optimistic UI. Data persistence can be achieved by using storage providers that store the data through a JSON in
36 lines (35 loc) • 1.44 kB
JavaScript
import get from "./index2.mjs";
import set from "./index4.mjs";
//#region src/utils/project.ts
/**
* Projects the fields of an object based on a specified fields configuration.
* Supports inclusion (`1`) and exclusion (`0`) of specific fields. Creates a new object
* with the desired fields included or excluded, based on the configuration.
* @template T - The type of the object being projected.
* @param item - The original object to project fields from.
* @param fields - An object defining the fields to include (`1`) or exclude (`0`).
* - Keys are the field names, and values are either `1` (include) or `0` (exclude).
* @returns A new object with the specified fields included or excluded.
* - If all fields are set to `0`, the excluded fields are removed from the result.
* - If fields are set to `1`, only the included fields are retained.
*/
function project(item, fields) {
if (Object.values(fields).every((value) => value === 0)) {
const result = { ...item };
Object.keys(fields).forEach((key) => {
if (get(item, key) === void 0) return;
set(result, key, void 0, true);
});
return result;
}
const result = {};
Object.entries(fields).forEach(([key, value]) => {
const fieldValue = get(item, key);
if (fieldValue === void 0) return;
if (fieldValue == null && value !== 1) return;
set(result, key, value === 1 ? fieldValue : void 0);
});
return result;
}
//#endregion
export { project as default };