_define-length.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. "use strict";
  2. var toPosInt = require("../number/to-pos-integer");
  3. var test = function (arg1, arg2) { return arg2; };
  4. var desc, defineProperty, generate, mixin;
  5. try {
  6. Object.defineProperty(test, "length", {
  7. configurable: true,
  8. writable: false,
  9. enumerable: false,
  10. value: 1
  11. });
  12. }
  13. catch (ignore) {}
  14. if (test.length === 1) {
  15. // ES6
  16. desc = { configurable: true, writable: false, enumerable: false };
  17. defineProperty = Object.defineProperty;
  18. module.exports = function (fn, length) {
  19. length = toPosInt(length);
  20. if (fn.length === length) return fn;
  21. desc.value = length;
  22. return defineProperty(fn, "length", desc);
  23. };
  24. } else {
  25. mixin = require("../object/mixin");
  26. generate = (function () {
  27. var cache = [];
  28. return function (length) {
  29. var args, i = 0;
  30. if (cache[length]) return cache[length];
  31. args = [];
  32. while (length--) args.push("a" + (++i).toString(36));
  33. // eslint-disable-next-line no-new-func
  34. return new Function(
  35. "fn",
  36. "return function (" + args.join(", ") + ") { return fn.apply(this, arguments); };"
  37. );
  38. };
  39. })();
  40. module.exports = function (src, length) {
  41. var target;
  42. length = toPosInt(length);
  43. if (src.length === length) return src;
  44. target = generate(length)(src);
  45. try { mixin(target, src); }
  46. catch (ignore) {}
  47. return target;
  48. };
  49. }