devextreme
Version:
JavaScript/TypeScript Component Suite for Responsive Web Development
609 lines (608 loc) • 18.6 kB
JavaScript
/**
* DevExtreme (esm/__internal/data/array_query.js)
* Version: 26.1.6
* Build date: Fri Oct 16 2026
*
* Copyright (c) 2012 - 2026 Developer Express Inc. ALL RIGHTS RESERVED
* Read about DevExtreme licensing here: https://js.devexpress.com/Licensing/
*/
import {
errors,
handleError as handleDataError
} from "../../common/data/errors";
import {
aggregators,
isConjunctiveOperator as isConjunctiveOperatorChecker,
isGroupCriterion,
isUnaryOperation,
isUniformEqualsByOr,
normalizeBinaryCriterion
} from "../../common/data/utils";
import {
compileGetter,
toComparable
} from "../../core/utils/data";
import {
Deferred
} from "../../core/utils/deferred";
import {
each,
map
} from "../../core/utils/iterator";
import {
isDefined,
isFunction,
isString
} from "../../core/utils/type";
const toGetter = expr => {
const getter = compileGetter(expr);
return getter
};
const isPredicate = criteria => isFunction(criteria);
class Iterator {
toArray() {
const result = [];
this.reset();
while (this.next()) {
result.push(this.current())
}
return result
}
countable() {
return false
}
}
class ArrayIterator extends Iterator {
constructor(array) {
super();
this.array = array;
this.index = -1
}
next() {
if (this.index + 1 < this.array.length) {
this.index += 1;
return true
}
return false
}
current() {
return this.array[this.index]
}
reset() {
this.index = -1
}
toArray() {
return this.array.slice(0)
}
countable() {
return true
}
count() {
return this.array.length
}
}
class WrappedIterator extends Iterator {
constructor(iter) {
super();
this.iter = iter
}
next() {
return this.iter.next()
}
current() {
return this.iter.current()
}
reset() {
this.iter.reset()
}
}
class MapIterator extends WrappedIterator {
constructor(iter, mapper) {
super(iter);
this.index = -1;
this.mapper = mapper
}
current() {
return this.mapper(super.current(), this.index)
}
next() {
const hasNext = super.next();
if (hasNext) {
this.index += 1
}
return hasNext
}
}
const defaultCompare = (xValue, yValue, options) => {
if (isString(xValue) && isString(yValue) && (null !== options && void 0 !== options && options.locale || null !== options && void 0 !== options && options.collatorOptions)) {
const collator = new Intl.Collator((null === options || void 0 === options ? void 0 : options.locale) || void 0, (null === options || void 0 === options ? void 0 : options.collatorOptions) || void 0);
return collator.compare(xValue, yValue)
}
const x = toComparable(xValue, false, options);
const y = toComparable(yValue, false, options);
if (null === x) {
return null === y ? 0 : -1
}
if (null === y) {
return 1
}
if (void 0 === x) {
return void 0 === y ? 0 : 1
}
if (void 0 === y) {
return -1
}
if (x < y) {
return -1
}
if (x > y) {
return 1
}
return 0
};
class SortIterator extends Iterator {
constructor(iter, getter, desc, compare) {
super();
this.langParams = iter.langParams;
let sourceIter = iter;
if (!(sourceIter instanceof MapIterator)) {
sourceIter = new MapIterator(sourceIter, this._wrap);
sourceIter.langParams = this.langParams
}
this.iter = sourceIter;
this.rules = [{
getter: getter,
desc: desc,
compare: compare,
langParams: this.langParams
}]
}
thenBy(getter, desc, compare) {
const result = new SortIterator(this.sortedIter || this.iter, getter, desc, compare);
if (!this.sortedIter) {
result.rules = this.rules.concat(result.rules)
}
return result
}
next() {
return this._ensureSorted().next()
}
current() {
return this._ensureSorted().current()
}
reset() {
delete this.sortedIter
}
countable() {
return this.sortedIter || this.iter.countable()
}
count() {
if (this.sortedIter) {
return this.sortedIter.count()
}
return this.iter.count()
}
_ensureSorted() {
const {
sortedIter: sortedIter
} = this;
if (sortedIter) {
return sortedIter
}
const rules = this.rules.map(rule => {
const getter = toGetter(rule.getter);
rule.getter = getter;
return Object.assign({}, rule, {
getter: getter
})
});
const result = new MapIterator(new ArrayIterator(this.iter.toArray().sort((x, y) => this._compare(x, y, rules))), this._unwrap);
this.sortedIter = result;
return result
}
_wrap(record, index) {
return {
index: index,
value: record
}
}
_unwrap(wrappedItem) {
return wrappedItem.value
}
_getDefaultCompare(langParams) {
return (xValue, yValue) => defaultCompare(xValue, yValue, langParams)
}
_compare(x, y, rules) {
const xIndex = x.index;
const yIndex = y.index;
const xRecord = x.value;
const yRecord = y.value;
if (xRecord === yRecord) {
return xIndex - yIndex
}
for (const rule of rules) {
const xValue = rule.getter(xRecord);
const yValue = rule.getter(yRecord);
const compare = rule.compare || this._getDefaultCompare(rule.langParams);
const compareResult = compare(xValue, yValue);
if (compareResult) {
return rule.desc ? -compareResult : compareResult
}
}
return xIndex - yIndex
}
}
const compileCriteria = function() {
let langParams = {};
const toCriteriaComparable = value => {
const result = toComparable(value, false, langParams);
return result
};
const toCriteriaString = value => {
const result = toComparable(value, false, langParams);
return result
};
const useStrictComparison = value => "" === value || 0 === value || false === value;
const compileEquals = (getter, value, negate) => obj => {
const objValue = toCriteriaComparable(getter(obj));
let result = useStrictComparison(value) ? objValue === value : objValue == value;
if (negate) {
result = !result
}
return result
};
const compileGroup = crit => {
if (isUniformEqualsByOr(crit)) {
return (crit => {
const getter = toGetter(crit[0][0]);
const filterValues = crit.reduce((acc, item, i) => {
if (i % 2 === 0) {
acc.push(toCriteriaComparable(item[2]))
}
return acc
}, []);
return obj => {
const value = toCriteriaComparable(getter(obj));
return filterValues.some(filterValue => useStrictComparison(filterValue) ? value === filterValue : value == filterValue)
}
})(crit)
}
const ops = [];
let isConjunctiveOperator = false;
let isConjunctiveNextOperator = false;
each(crit, (_, item) => {
if (Array.isArray(item) || isFunction(item)) {
if (ops.length > 1 && isConjunctiveOperator !== isConjunctiveNextOperator) {
throw errors.Error("E4019")
}
ops.push(compileCriteria(item, langParams));
isConjunctiveOperator = isConjunctiveNextOperator;
isConjunctiveNextOperator = true
} else {
isConjunctiveNextOperator = isConjunctiveOperatorChecker(item)
}
});
return d => {
let result = isConjunctiveOperator;
for (let i = 0; i < ops.length; i += 1) {
if (ops[i](d) !== isConjunctiveOperator) {
result = !isConjunctiveOperator;
break
}
}
return result
}
};
const stringify = value => {
if (!isDefined(value)) {
return ""
}
if (langParams.locale) {
const localized = value.toLocaleString(langParams.locale);
return localized
}
return value.toString()
};
return (crit, options) => {
langParams = options || {};
if (isPredicate(crit)) {
return crit
}
if (isGroupCriterion(crit)) {
return compileGroup(crit)
}
if (isUnaryOperation(crit)) {
return (crit => {
const op = crit[0];
const criteria = compileCriteria(crit[1], langParams);
if ("!" === op) {
return obj => !criteria(obj)
}
throw errors.Error("E4003", op)
})(crit)
}
return (criterion => {
const crit = normalizeBinaryCriterion(criterion);
const getter = toGetter(crit[0]);
const op = crit[1];
const value = toCriteriaComparable(crit[2]);
const stringValue = toCriteriaString(crit[2]);
const compare = (obj, operatorFn) => {
const objValue = toCriteriaComparable(getter(obj));
return (null == value || null == objValue) && value !== objValue ? false : operatorFn(objValue, value)
};
switch (op.toLowerCase()) {
case "=":
return compileEquals(getter, value);
case "<>":
return compileEquals(getter, value, true);
case ">":
return obj => compare(obj, (a, b) => a > b);
case "<":
return obj => compare(obj, (a, b) => a < b);
case ">=":
return obj => compare(obj, (a, b) => a >= b);
case "<=":
return obj => compare(obj, (a, b) => a <= b);
case "startswith":
return obj => toCriteriaString(stringify(getter(obj))).startsWith(stringValue);
case "endswith":
return obj => toCriteriaString(stringify(getter(obj))).endsWith(stringValue);
case "contains":
return obj => toCriteriaString(stringify(getter(obj))).includes(stringValue);
case "notcontains":
return obj => !toCriteriaString(stringify(getter(obj))).includes(stringValue)
}
throw errors.Error("E4003", op)
})(crit)
}
}();
class FilterIterator extends WrappedIterator {
constructor(iter, criteria) {
super(iter);
this.langParams = iter.langParams;
this.criteria = compileCriteria(criteria, this.langParams)
}
next() {
while (this.iter.next()) {
if (this.criteria(this.current())) {
return true
}
}
return false
}
}
class GroupIterator extends Iterator {
constructor(iter, getter) {
super();
this.iter = iter;
this.getter = getter
}
next() {
return this._ensureGrouped().next()
}
current() {
return this._ensureGrouped().current()
}
reset() {
delete this.groupedIter
}
countable() {
return !!this.groupedIter
}
count() {
return this._ensureGrouped().count()
}
_ensureGrouped() {
const {
groupedIter: groupedIter
} = this;
if (groupedIter) {
return groupedIter
}
const hash = {};
const keys = [];
const {
iter: iter
} = this;
const getter = toGetter(this.getter);
iter.reset();
while (iter.next()) {
const current = iter.current();
const key = getter(current);
if (key in hash) {
hash[key].push(current)
} else {
hash[key] = [current];
keys.push(key)
}
}
const groups = map(keys, key => ({
key: key,
items: hash[key]
}));
const result = new ArrayIterator(groups);
this.groupedIter = result;
return result
}
}
class SelectIterator extends WrappedIterator {
constructor(iter, getter) {
super(iter);
this.getter = toGetter(getter)
}
current() {
return this.getter(super.current())
}
countable() {
return this.iter.countable()
}
count() {
return this.iter.count()
}
}
class SliceIterator extends WrappedIterator {
constructor(iter, skip, take) {
super(iter);
this.skip = Math.max(0, skip);
this.take = Math.max(0, take);
this.pos = 0
}
next() {
if (this.pos >= this.skip + this.take) {
return false
}
while (this.pos < this.skip && this.iter.next()) {
this.pos += 1
}
this.pos += 1;
return this.iter.next()
}
reset() {
super.reset();
this.pos = 0
}
countable() {
return this.iter.countable()
}
count() {
return Math.min(this.iter.count() - this.skip, this.take)
}
}
const arrayQueryImpl = function(source, options) {
const queryOptions = options || {};
const iter = source instanceof Iterator ? source : new ArrayIterator(source);
if (queryOptions.langParams) {
iter.langParams = queryOptions.langParams
}
const handleError = error => {
const handler = queryOptions.errorHandler;
if (handler) {
handler(error)
}
handleDataError(error)
};
const chainQuery = chainedIter => arrayQueryImpl(chainedIter, queryOptions);
const aggregateCore = aggregator => {
const d = Deferred().fail(handleError);
const {
step: step,
finalize: finalize
} = aggregator;
try {
iter.reset();
let accumulator = NaN;
if ("seed" in aggregator) {
accumulator = aggregator.seed
} else if (iter.next()) {
accumulator = iter.current()
}
while (iter.next()) {
accumulator = step(accumulator, iter.current())
}
d.resolve(finalize ? finalize(accumulator) : accumulator)
} catch (x) {
d.reject(x)
}
return d.promise()
};
const standardAggregate = name => {
const aggregator = aggregators[name];
return aggregateCore(aggregator)
};
const select = function() {
for (var _len2 = arguments.length, getters = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
getters[_key2] = arguments[_key2]
}
const [first] = getters;
const getter = isFunction(first) || Array.isArray(first) ? first : getters;
return chainQuery(new SelectIterator(iter, getter))
};
const selectProp = name => select(toGetter(name));
return {
toArray: () => iter.toArray(),
enumerate() {
const d = Deferred().fail(handleError);
try {
d.resolve(iter.toArray())
} catch (x) {
d.reject(x)
}
return d.promise()
},
setLangParams(langParams) {
iter.langParams = langParams
},
sortBy: (getter, desc, compare) => chainQuery(new SortIterator(iter, getter, desc, compare)),
thenBy(getter, desc, compare) {
if (iter instanceof SortIterator) {
return chainQuery(iter.thenBy(getter, desc, compare))
}
throw errors.Error("E4004")
},
filter() {
for (var _len3 = arguments.length, criteria = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
criteria[_key3] = arguments[_key3]
}
const [first] = criteria;
return chainQuery(new FilterIterator(iter, Array.isArray(first) ? first : criteria))
},
slice: (skip, take) => chainQuery(new SliceIterator(iter, skip, void 0 === take ? Number.MAX_VALUE : take)),
select: select,
groupBy: getter => chainQuery(new GroupIterator(iter, getter)),
aggregate: function() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key]
}
const [seedOrStep, ...rest] = args;
if (0 === rest.length) {
return aggregateCore({
step: seedOrStep
})
}
const [step, finalize] = rest;
return aggregateCore({
seed: seedOrStep,
step: step,
finalize: finalize
})
},
count() {
if (iter.countable()) {
const d = Deferred().fail(handleError);
try {
d.resolve(iter.count())
} catch (x) {
d.reject(x)
}
return d.promise()
}
return standardAggregate("count")
},
sum(getter) {
if (getter) {
return selectProp(getter).sum()
}
return standardAggregate("sum")
},
min(getter) {
if (getter) {
return selectProp(getter).min()
}
return standardAggregate("min")
},
max(getter) {
if (getter) {
return selectProp(getter).max()
}
return standardAggregate("max")
},
avg(getter) {
if (getter) {
return selectProp(getter).avg()
}
return standardAggregate("avg")
}
}
};
export default arrayQueryImpl;