_define-length.js 1.2 KB

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