source: node_modules/set-function-length/index.js

main
Last change on this file was d24f17c, checked in by Aleksandar Panovski <apano77@…>, 15 months ago

Initial commit

  • Property mode set to 100644
File size: 1.4 KB
Line 
1'use strict';
2
3var GetIntrinsic = require('get-intrinsic');
4var define = require('define-data-property');
5var hasDescriptors = require('has-property-descriptors')();
6var gOPD = require('gopd');
7
8var $TypeError = require('es-errors/type');
9var $floor = GetIntrinsic('%Math.floor%');
10
11/** @typedef {(...args: unknown[]) => unknown} Func */
12
13/** @type {<T extends Func = Func>(fn: T, length: number, loose?: boolean) => T} */
14module.exports = function setFunctionLength(fn, length) {
15 if (typeof fn !== 'function') {
16 throw new $TypeError('`fn` is not a function');
17 }
18 if (typeof length !== 'number' || length < 0 || length > 0xFFFFFFFF || $floor(length) !== length) {
19 throw new $TypeError('`length` must be a positive 32-bit integer');
20 }
21
22 var loose = arguments.length > 2 && !!arguments[2];
23
24 var functionLengthIsConfigurable = true;
25 var functionLengthIsWritable = true;
26 if ('length' in fn && gOPD) {
27 var desc = gOPD(fn, 'length');
28 if (desc && !desc.configurable) {
29 functionLengthIsConfigurable = false;
30 }
31 if (desc && !desc.writable) {
32 functionLengthIsWritable = false;
33 }
34 }
35
36 if (functionLengthIsConfigurable || functionLengthIsWritable || !loose) {
37 if (hasDescriptors) {
38 define(/** @type {Parameters<define>[0]} */ (fn), 'length', length, true, true);
39 } else {
40 define(/** @type {Parameters<define>[0]} */ (fn), 'length', length);
41 }
42 }
43 return fn;
44};
Note: See TracBrowser for help on using the repository browser.