index.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. 'use strict';
  2. var GetIntrinsic = require('get-intrinsic');
  3. var define = require('define-data-property');
  4. var hasDescriptors = require('has-property-descriptors')();
  5. var gOPD = require('gopd');
  6. var $TypeError = GetIntrinsic('%TypeError%');
  7. var $floor = GetIntrinsic('%Math.floor%');
  8. module.exports = function setFunctionLength(fn, length) {
  9. if (typeof fn !== 'function') {
  10. throw new $TypeError('`fn` is not a function');
  11. }
  12. if (typeof length !== 'number' || length < 0 || length > 0xFFFFFFFF || $floor(length) !== length) {
  13. throw new $TypeError('`length` must be a positive 32-bit integer');
  14. }
  15. var loose = arguments.length > 2 && !!arguments[2];
  16. var functionLengthIsConfigurable = true;
  17. var functionLengthIsWritable = true;
  18. if ('length' in fn && gOPD) {
  19. var desc = gOPD(fn, 'length');
  20. if (desc && !desc.configurable) {
  21. functionLengthIsConfigurable = false;
  22. }
  23. if (desc && !desc.writable) {
  24. functionLengthIsWritable = false;
  25. }
  26. }
  27. if (functionLengthIsConfigurable || functionLengthIsWritable || !loose) {
  28. if (hasDescriptors) {
  29. define(fn, 'length', length, true, true);
  30. } else {
  31. define(fn, 'length', length);
  32. }
  33. }
  34. return fn;
  35. };