UNPKG

@datastax/astra-db-ts

Version:
50 lines (49 loc) 1.55 kB
// Copyright Datastax, Inc // SPDX-License-Identifier: Apache-2.0 import { splitWithIncludesCheck } from '../../../lib/utils.js'; export const pullSafeProjection4Distinct = (path) => { const split = splitWithIncludesCheck(path, '.'); if (split.some(p => !p)) { throw new Error('Path cannot contain empty segments'); } let i, n; for (i = 0, n = split.length; i < n && isNaN(+split[i]); i++) { } split.length = i; return split.join('.'); }; export const mkDistinctPathExtractor = (path) => { const values = []; const extract = (path, index, value) => { if (value === undefined) { return; } if (index === path.length) { if (Array.isArray(value)) { values.push(...value); } else { values.push(value); } return; } const prop = path[index]; if (Array.isArray(value)) { const asInt = parseInt(prop, 10); if (isNaN(asInt)) { for (let i = 0, n = value.length; i < n; i++) { extract(path, index, value[i]); } } else if (asInt < value.length) { extract(path, index + 1, value[asInt]); } } else if (value && typeof value === 'object') { extract(path, index + 1, value[prop]); } }; return (doc) => { extract(splitWithIncludesCheck(path, '.'), 0, doc); return values; }; };