_define-length.js 1.3 KB

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