UNPKG

mingo

Version:

MongoDB query language for in-memory objects

27 lines (26 loc) 740 B
import { assert, isArray } from "../../util"; import { applyUpdate, DEFAULT_OPTIONS, walkExpression } from "./_internal"; function $pop(expr, arrayFilters = [], options = DEFAULT_OPTIONS) { for (const position of Object.values(expr)) { assert(position === 1 || position === -1, `$pop argument must be 1 or -1.`); } return (obj) => { return walkExpression( expr, arrayFilters, options, (val, node, queries) => { return applyUpdate(obj, node, queries, (o, k) => { const arr = o[k]; if (!isArray(arr) || !arr.length) return false; if (val === -1) arr.splice(0, 1); else arr.pop(); return true; }); } ); }; } export { $pop };