function.js 1.4 KB

12345678910111213141516171819202122232425262728293031
  1. 'use strict';
  2. const { getBooleanOption, cppdb } = require('../util');
  3. module.exports = function defineFunction(name, options, fn) {
  4. // Apply defaults
  5. if (options == null) options = {};
  6. if (typeof options === 'function') { fn = options; options = {}; }
  7. // Validate arguments
  8. if (typeof name !== 'string') throw new TypeError('Expected first argument to be a string');
  9. if (typeof fn !== 'function') throw new TypeError('Expected last argument to be a function');
  10. if (typeof options !== 'object') throw new TypeError('Expected second argument to be an options object');
  11. if (!name) throw new TypeError('User-defined function name cannot be an empty string');
  12. // Interpret options
  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 = fn.length;
  21. if (!Number.isInteger(argCount) || argCount < 0) throw new TypeError('Expected function.length to be a positive integer');
  22. if (argCount > 100) throw new RangeError('User-defined functions cannot have more than 100 arguments');
  23. }
  24. this[cppdb].function(fn, name, argCount, safeIntegers, deterministic, directOnly);
  25. return this;
  26. };