index.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. 'use strict';
  2. var callBind = require('../');
  3. var hasStrictMode = require('has-strict-mode')();
  4. var forEach = require('for-each');
  5. var inspect = require('object-inspect');
  6. var v = require('es-value-fixtures');
  7. var test = require('tape');
  8. test('callBindBasic', function (t) {
  9. forEach(v.nonFunctions, function (nonFunction) {
  10. t['throws'](
  11. // @ts-expect-error
  12. function () { callBind([nonFunction]); },
  13. TypeError,
  14. inspect(nonFunction) + ' is not a function'
  15. );
  16. });
  17. var sentinel = { sentinel: true };
  18. /** @type {<T>(this: T, a: number, b: number) => [T | undefined, number, number]} */
  19. var func = function (a, b) {
  20. // eslint-disable-next-line no-invalid-this
  21. return [!hasStrictMode && this === global ? undefined : this, a, b];
  22. };
  23. t.equal(func.length, 2, 'original function length is 2');
  24. /** type {(thisArg: unknown, a: number, b: number) => [unknown, number, number]} */
  25. var bound = callBind([func]);
  26. /** type {((a: number, b: number) => [sentinel, typeof a, typeof b])} */
  27. var boundR = callBind([func, sentinel]);
  28. /** type {((b: number) => [sentinel, number, typeof b])} */
  29. var boundArg = callBind([func, sentinel, 1]);
  30. // @ts-expect-error
  31. t.deepEqual(bound(), [undefined, undefined, undefined], 'bound func with no args');
  32. // @ts-expect-error
  33. t.deepEqual(func(), [undefined, undefined, undefined], 'unbound func with too few args');
  34. // @ts-expect-error
  35. t.deepEqual(bound(1, 2), [hasStrictMode ? 1 : Object(1), 2, undefined], 'bound func too few args');
  36. // @ts-expect-error
  37. t.deepEqual(boundR(), [sentinel, undefined, undefined], 'bound func with receiver, with too few args');
  38. // @ts-expect-error
  39. t.deepEqual(boundArg(), [sentinel, 1, undefined], 'bound func with receiver and arg, with too few args');
  40. t.deepEqual(func(1, 2), [undefined, 1, 2], 'unbound func with right args');
  41. t.deepEqual(bound(1, 2, 3), [hasStrictMode ? 1 : Object(1), 2, 3], 'bound func with right args');
  42. t.deepEqual(boundR(1, 2), [sentinel, 1, 2], 'bound func with receiver, with right args');
  43. t.deepEqual(boundArg(2), [sentinel, 1, 2], 'bound func with receiver and arg, with right arg');
  44. // @ts-expect-error
  45. t.deepEqual(func(1, 2, 3), [undefined, 1, 2], 'unbound func with too many args');
  46. // @ts-expect-error
  47. t.deepEqual(bound(1, 2, 3, 4), [hasStrictMode ? 1 : Object(1), 2, 3], 'bound func with too many args');
  48. // @ts-expect-error
  49. t.deepEqual(boundR(1, 2, 3), [sentinel, 1, 2], 'bound func with receiver, with too many args');
  50. // @ts-expect-error
  51. t.deepEqual(boundArg(2, 3), [sentinel, 1, 2], 'bound func with receiver and arg, with too many args');
  52. t.end();
  53. });