UNPKG

2.61 kBJavaScriptView Raw
1'use strict';
2var uncurryThis = require('../internals/function-uncurry-this');
3var fails = require('../internals/fails');
4var isCallable = require('../internals/is-callable');
5var hasOwn = require('../internals/has-own-property');
6var DESCRIPTORS = require('../internals/descriptors');
7var CONFIGURABLE_FUNCTION_NAME = require('../internals/function-name').CONFIGURABLE;
8var inspectSource = require('../internals/inspect-source');
9var InternalStateModule = require('../internals/internal-state');
10
11var enforceInternalState = InternalStateModule.enforce;
12var getInternalState = InternalStateModule.get;
13var $String = String;
14// eslint-disable-next-line es/no-object-defineproperty -- safe
15var defineProperty = Object.defineProperty;
16var stringSlice = uncurryThis(''.slice);
17var replace = uncurryThis(''.replace);
18var join = uncurryThis([].join);
19
20var CONFIGURABLE_LENGTH = DESCRIPTORS && !fails(function () {
21 return defineProperty(function () { /* empty */ }, 'length', { value: 8 }).length !== 8;
22});
23
24var TEMPLATE = String(String).split('String');
25
26var makeBuiltIn = module.exports = function (value, name, options) {
27 if (stringSlice($String(name), 0, 7) === 'Symbol(') {
28 name = '[' + replace($String(name), /^Symbol\(([^)]*)\).*$/, '$1') + ']';
29 }
30 if (options && options.getter) name = 'get ' + name;
31 if (options && options.setter) name = 'set ' + name;
32 if (!hasOwn(value, 'name') || (CONFIGURABLE_FUNCTION_NAME && value.name !== name)) {
33 if (DESCRIPTORS) defineProperty(value, 'name', { value: name, configurable: true });
34 else value.name = name;
35 }
36 if (CONFIGURABLE_LENGTH && options && hasOwn(options, 'arity') && value.length !== options.arity) {
37 defineProperty(value, 'length', { value: options.arity });
38 }
39 try {
40 if (options && hasOwn(options, 'constructor') && options.constructor) {
41 if (DESCRIPTORS) defineProperty(value, 'prototype', { writable: false });
42 // in V8 ~ Chrome 53, prototypes of some methods, like `Array.prototype.values`, are non-writable
43 } else if (value.prototype) value.prototype = undefined;
44 } catch (error) { /* empty */ }
45 var state = enforceInternalState(value);
46 if (!hasOwn(state, 'source')) {
47 state.source = join(TEMPLATE, typeof name == 'string' ? name : '');
48 } return value;
49};
50
51// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
52// eslint-disable-next-line no-extend-native -- required
53Function.prototype.toString = makeBuiltIn(function toString() {
54 return isCallable(this) && getInternalState(this).source || inspectSource(this);
55}, 'toString');