UNPKG

@njs-lib/select-query

Version:

Library for flexible querying and manipulation of object collections.

319 lines (317 loc) 13.4 kB
"use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var __accessCheck = (obj, member, msg) => { if (!member.has(obj)) throw TypeError("Cannot " + msg); }; var __privateGet = (obj, member, getter) => { __accessCheck(obj, member, "read from private field"); return getter ? getter.call(obj) : member.get(obj); }; var __privateAdd = (obj, member, value) => { if (member.has(obj)) throw TypeError("Cannot add the same private member more than once"); member instanceof WeakSet ? member.add(obj) : member.set(obj, value); }; var __privateSet = (obj, member, value, setter) => { __accessCheck(obj, member, "write to private field"); setter ? setter.call(obj, value) : member.set(obj, value); return value; }; var __privateMethod = (obj, member, method) => { __accessCheck(obj, member, "access private method"); return method; }; // src/index.ts var src_exports = {}; __export(src_exports, { SelectQuery: () => SelectQuery }); module.exports = __toCommonJS(src_exports); // src/select-query.ts var operators = [ "===", "!==", "<", "<=", ">", ">=", "like", "^like", "like$" ]; var _collection, _equal, equal_fn, _lessThan, lessThan_fn, _lessThanOrEqualTo, lessThanOrEqualTo_fn, _greaterThan, greaterThan_fn, _greaterThanOrEqualTo, greaterThanOrEqualTo_fn, _like, like_fn; var _SelectQuery = class _SelectQuery { /** * Creates a new SelectQuery instance with the given collection. * @param {T[]} collection - An array of objects to be used for querying. * @throws {Error} Throws an error if the input is not an array of objects. */ constructor(collection) { /** * Checks if the specified property of an item is equal to a given value. * @template K - The type of the property to compare. * @param {T[K]} itemValue - The value of the property to compare. * @param {T[K]} value - The value to compare against. * @returns {boolean} - Returns true if the property values are equal, otherwise returns false. */ __privateAdd(this, _equal); /** * Checks if the specified property of an item is less than a given value. * @template K - The type of the property to compare. * @param {T[K]} itemValue - The value of the property to compare. * @param {T[K]} value - The value to compare against. * @returns {boolean} - Returns true if the property value is less than the given value, otherwise returns false. */ __privateAdd(this, _lessThan); /** * Checks if the specified property of an item is less than or equal to a given value. * @template K - The type of the property to compare. * @param {T[K]} itemValue - The value of the property to compare. * @param {T[K]} value - The value to compare against. * @returns {boolean} - Returns true if the property value is less than or equal to the given value, otherwise returns false. */ __privateAdd(this, _lessThanOrEqualTo); /** * Checks if the specified property of an item is greater than a given value. * @template K - The type of the property to compare. * @param {T[K]} itemValue - The value of the property to compare. * @param {T[K]} value - The value to compare against. * @returns {boolean} - Returns true if the property value is greater than the given value, otherwise returns false. */ __privateAdd(this, _greaterThan); /** * Checks if the specified property of an item is greater than or equal to a given value. * @template K - The type of the property to compare. * @param {T[K]} itemValue - The value of the property to compare. * @param {T[K]} value - The value to compare against. * @returns {boolean} - Returns true if the property value is greater than or equal to the given value, otherwise returns false. */ __privateAdd(this, _greaterThanOrEqualTo); /** * Checks if the specified property of an item is like a given value with optional type-based matching. * @template K - The type of the property to compare. * @param {T[K]} itemValue - The value of the property to compare. * @param {T[K]} value - The value to compare against. * @param {'^like' | 'like$'} [type] - The optional matching type: * - ^like matches if the property value starts with the given value. * - like$ matches if the property value ends with the given value. * - if not provided or set to 'like', it matches if the property value contains the given value. * @returns {boolean} - Returns true if the property value matches the given value based on the specified type, otherwise returns false. */ __privateAdd(this, _like); __privateAdd(this, _collection, void 0); if (!Array.isArray(collection) || collection.some((item) => typeof item !== "object" || item === null)) { throw new Error("The collection should be an array of objects."); } __privateSet(this, _collection, collection); } /** * Gets the array of valid operators for comparisons. * @returns {Operator[]} - An array containing all valid operators for comparisons. * @description * This method returns an array of predefined operators that can be used for comparisons, * such as '===', '!==', '<', '<=', '>', '>=', 'like', '^like', and 'like$'. * These operators are useful in scenarios where you need to dynamically select * an operator for a comparison operation. */ static getOperators() { return operators; } /** * Gets the first element of the collection. * @returns {T | undefined} - The first element of the collection, or undefined if the collection is empty. */ first() { return __privateGet(this, _collection)[0]; } /** * Gets the last element of the collection. * @returns {T | undefined} - The last element of the collection, or undefined if the collection is empty. */ last() { return __privateGet(this, _collection)[__privateGet(this, _collection).length - 1]; } /** * Gets all elements in the collection. * @returns {T[]} - An array containing all elements in the collection. */ get() { return __privateGet(this, _collection); } /** * Gets the number of elements in the collection. * @returns {number} - The number of elements in the collection. */ count() { return __privateGet(this, _collection).length; } /** * Limits the number of objects in the collection to a specified maximum. * @param {number} limit - The maximum number of objects to include in the collection. * @returns {SelectQuery<T>} - A new SelectQuery instance with a limited number of objects. */ limit(limit) { if (limit <= 0) { throw new Error("Limit must be a positive number."); } return new _SelectQuery(__privateGet(this, _collection).slice(0, limit)); } /** * Offsets the collection by a specified number of objects. * @param {number} offset - The number of objects to skip from the beginning of the collection. * @returns {SelectQuery<T>} - A new SelectQuery instance with objects after the specified offset. */ offset(offset) { if (offset < 0 || offset >= __privateGet(this, _collection).length) { throw new Error("Offset is out of range."); } return new _SelectQuery(__privateGet(this, _collection).slice(offset)); } /** * Paginates the collection based on a page number and page size. * @param {number} num - The page number (1-based). * @param {number} size - The number of objects per page. * @returns {SelectQuery<T>} - A new SelectQuery instance with objects for the specified page. */ paginate(num, size) { return this.offset((Math.max(num, 1) - 1) * size).limit(size); } /** * Calculates the sum of the values for a specified property in the collection. * This method iterates over each object in the collection, accessing the value * of the specified property. It sums these values and returns the total. If a * property's value is `undefined`, `null` it will be ignored * (treated as 0) in the summation. * @template K - The type of the key. * @param {keyof T} key - The property key whose values are to be summed up. * @returns {number} The sum of the property values. * @throws {Error} Throws an error if any property value is not a number. */ sum(key) { return __privateGet(this, _collection).reduce((acc, item) => { const value = item[key]; if (value === void 0 || value === null) { return acc; } if (typeof value !== "number") { throw new Error(`Sum operation failed: the property '${String(key)}' must be a number in every item of the collection.`); } return acc + value; }, 0); } /** * Selects specific properties from each object in the collection and returns a new SelectQuery instance. * @template K - The keys to select from the objects in the collection. * @param {...K} keys - The keys (properties) to select. * @returns {SelectQuery<Pick<T, K>>} - A new SelectQuery instance with objects containing only the selected keys. */ select(...keys) { return new _SelectQuery(__privateGet(this, _collection).map((item) => { return keys.reduce((acc, key) => ({ ...acc, [key]: item[key] }), {}); })); } /** * Groups elements in a collection based on a specified key. * @template K - The type of the key. * @param {K} key - The key (property name) by which to group elements. * @returns {Record<T[K], T>} - An object with keys as unique values from the collection based on the specified key, * and values as the corresponding objects from the collection. */ keyBy(key) { return __privateGet(this, _collection).reduce((acc, item) => { const keyValue = item[key]; return key in item ? { ...acc, [keyValue]: item } : acc; }, {}); } /** * Filters the collection based on a specified condition. * @template K - The type of the property to compare. * @param {keyof T} key - The key (property name) to compare. * @param {Operator} operator - The comparison operator. * @param {T[keyof T]} value - The value to compare against. * @returns {SelectQuery<T>} - A new SelectQuery instance with filtered elements. */ where(key, operator, value) { return new _SelectQuery(__privateGet(this, _collection).filter((item) => { const itemValue = item[key]; switch (operator) { case "===": return __privateMethod(this, _equal, equal_fn).call(this, itemValue, value); case "!==": return !__privateMethod(this, _equal, equal_fn).call(this, itemValue, value); case "<": return __privateMethod(this, _lessThan, lessThan_fn).call(this, itemValue, value); case "<=": return __privateMethod(this, _lessThanOrEqualTo, lessThanOrEqualTo_fn).call(this, itemValue, value); case ">": return __privateMethod(this, _greaterThan, greaterThan_fn).call(this, itemValue, value); case ">=": return __privateMethod(this, _greaterThanOrEqualTo, greaterThanOrEqualTo_fn).call(this, itemValue, value); case "like": return __privateMethod(this, _like, like_fn).call(this, itemValue, value); case "^like": return __privateMethod(this, _like, like_fn).call(this, itemValue, value, "^like"); case "like$": return __privateMethod(this, _like, like_fn).call(this, itemValue, value, "like$"); default: throw new Error(`Unknown operator: ${operator}`); } })); } }; _collection = new WeakMap(); _equal = new WeakSet(); equal_fn = function(itemValue, value) { return itemValue === value; }; _lessThan = new WeakSet(); lessThan_fn = function(itemValue, value) { return itemValue < value; }; _lessThanOrEqualTo = new WeakSet(); lessThanOrEqualTo_fn = function(itemValue, value) { return itemValue <= value; }; _greaterThan = new WeakSet(); greaterThan_fn = function(itemValue, value) { return itemValue > value; }; _greaterThanOrEqualTo = new WeakSet(); greaterThanOrEqualTo_fn = function(itemValue, value) { return itemValue >= value; }; _like = new WeakSet(); like_fn = function(itemValue, value, type) { const v1 = itemValue.toString().toLowerCase(); const v2 = value.toString().toLowerCase(); if (type === "^like") { return v1.startsWith(v2); } if (type === "like$") { return v1.endsWith(v2); } return v1.includes(v2); }; var SelectQuery = _SelectQuery; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { SelectQuery }); //# sourceMappingURL=index.js.map