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