aggregate.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. 'use strict';
  2. const { getBooleanOption, cppdb } = require('../util');
  3. module.exports = function defineAggregate(name, options) {
  4. // Validate arguments
  5. if (typeof name !== 'string') throw new TypeError('Expected first argument to be a string');
  6. if (typeof options !== 'object' || options === null) throw new TypeError('Expected second argument to be an options object');
  7. if (!name) throw new TypeError('User-defined function name cannot be an empty string');
  8. // Interpret options
  9. const start = 'start' in options ? options.start : null;
  10. const step = getFunctionOption(options, 'step', true);
  11. const inverse = getFunctionOption(options, 'inverse', false);
  12. const result = getFunctionOption(options, 'result', false);
  13. const safeIntegers = 'safeIntegers' in options ? +getBooleanOption(options, 'safeIntegers') : 2;
  14. const deterministic = getBooleanOption(options, 'deterministic');
  15. const directOnly = getBooleanOption(options, 'directOnly');
  16. const varargs = getBooleanOption(options, 'varargs');
  17. let argCount = -1;
  18. // Determine argument count
  19. if (!varargs) {
  20. argCount = Math.max(getLength(step), inverse ? getLength(inverse) : 0);
  21. if (argCount > 0) argCount -= 1;
  22. if (argCount > 100) throw new RangeError('User-defined functions cannot have more than 100 arguments');
  23. }
  24. this[cppdb].aggregate(start, step, inverse, result, name, argCount, safeIntegers, deterministic, directOnly);
  25. return this;
  26. };
  27. const getFunctionOption = (options, key, required) => {
  28. const value = key in options ? options[key] : null;
  29. if (typeof value === 'function') return value;
  30. if (value != null) throw new TypeError(`Expected the "${key}" option to be a function`);
  31. if (required) throw new TypeError(`Missing required option "${key}"`);
  32. return null;
  33. };
  34. const getLength = ({ length }) => {
  35. if (Number.isInteger(length) && length >= 0) return length;
  36. throw new TypeError('Expected function.length to be a positive integer');
  37. };