UNPKG

mingo

Version:

MongoDB query language for in-memory objects

24 lines (23 loc) 890 B
import { computeValue } from "../../../core/_internal"; import { assert, isArray, isInteger, isNil } from "../../../util"; import { errExpectArray, errExpectNumber, INT_OPTS } from "../_internal"; const OP = "$arrayElemAt"; const $arrayElemAt = (obj, expr, options) => { assert(isArray(expr) && expr.length === 2, `${OP} expects array(2)`); const args = computeValue(obj, expr, null, options); if (args.some(isNil)) return null; const foe = options.failOnError; const [arr, index] = args; if (!isArray(arr)) return errExpectArray(foe, `${OP} arg1 <array>`); if (!isInteger(index)) return errExpectNumber(foe, `${OP} arg2 <index>`, INT_OPTS.int); if (index < 0 && Math.abs(index) <= arr.length) { return arr[(index + arr.length) % arr.length]; } else if (index >= 0 && index < arr.length) { return arr[index]; } return void 0; }; export { $arrayElemAt };