UNPKG

squid

Version:

Provides SQL tagged template strings and a schema definition function.

79 lines (78 loc) 2.36 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Escape the given identifier. */ function escapeIdentifier(identifier) { if (identifier.charAt(0) === '"' && identifier.charAt(identifier.length - 1) === '"') { identifier = identifier.substr(1, identifier.length - 2); } if (identifier.includes('"')) { throw new Error(`Invalid identifier: ${identifier}`); } return `"${identifier}"`; } exports.escapeIdentifier = escapeIdentifier; /** * Filter out all undefined keys in the given record. */ function filterUndefined(object) { const filteredEntries = Object.entries(object).filter(([_, v]) => v !== undefined); // Object.fromEntries was added in ECMA2019 return filteredEntries.reduce((acc, [k, v]) => (Object.assign(Object.assign({}, acc), { [k]: v })), {}); } exports.filterUndefined = filterUndefined; /** * Merge two lists, alternating between elements. * * @example * mergeLists([x1, x2, x3], [y1, y2, y3]) == [x1, y1, x2, y2, x3, y3] */ function mergeLists(list1, list2) { const result = []; for (let i = 0; i < Math.max(list1.length, list2.length); i++) { const elem1 = list1[i]; if (elem1 !== undefined) { result.push(elem1); } const elem2 = list2[i]; if (elem2 !== undefined) { result.push(elem2); } } return result; } exports.mergeLists = mergeLists; function objectKeys(object) { return new Set(Object.keys(object)); } function areSetsEqual(set1, set2) { const difference = new Set(set1); for (const elem of set2) { if (difference.has(elem)) { difference.delete(elem); } else { return false; } } return difference.size === 0; } /** * Get the keys from the given list of objects. Checks that the objects all * have the same keys. */ function extractKeys(objects) { if (objects.length === 0) { throw new Error("Cannot call extractKeys on empty list"); } const keys = objectKeys(objects[0]); for (const o of objects) { const oKeys = objectKeys(o); if (!areSetsEqual(keys, oKeys)) { throw new Error(`Objects have different keys: ${JSON.stringify(objects)}`); } } return Array.from(keys); } exports.extractKeys = extractKeys;