Remove duplicated functions inside different if within a function? I have a function :
function __throwError(func) {
  if (func.length === 1) {
    function passNumber() {
      func(0);
    }
    function passString() {
      func(&quot;item&quot;);
    }
    function passEmptyArray() {
      func([]);
    }
    function passUndefinedOrNull() {
      func(undefined || null);
    }
    expect(passNumber).toThrowError(&quot;The parameter should be an array&quot;);
    expect(passString).toThrowError(&quot;The parameter should be an array&quot;);
    expect(passEmptyArray).toThrowError(&quot;The array is empty&quot;);
    expect(passUndefinedOrNull).toThrowError(&quot;The parameter is null or undefined&quot;);
  }
  if (func.length === 2) {
    function passNumber() {
      func(0, 1);
    }
    function passString() {
      func(&quot;item&quot;, 1);
    }
    function passEmptyArray() {
      func([], 1);
    }
    function passUndefinedOrNull() {
      func(undefined || null, 1);
    }
    expect(passNumber).toThrowError(&quot;The parameter should be an array&quot;);
    expect(passString).toThrowError(&quot;The parameter should be an array&quot;);
    expect(passEmptyArray).toThrowError(&quot;The array is empty&quot;);
    expect(passUndefinedOrNull).toThrowError(&quot;The parameter is null or undefined&quot;);
  }
}

You may notice that there are duplicated passNumber,passString,passEmpty inside different if statements and each function call different callback function func.
How do I remove duplicated functions: passNumber,passString,passEmpty and just have once call with different parameters ?
The only difference between the two parts is that the second part has an additional parameter 1? You can provide an array with the original param, if function.length is 2, push 1 into it. the just call func.apply(null, params).
Here is a solution base on the idea:
function __throwError (func) {
  const testcases = [
    new TestCase(func, 0, 'The parameter should be an array'),
    new TestCase(func, 'item', 'The parameter should be an array'),
    new TestCase(func, [], 'The array is empty'),
    new TestCase(func, undefined, 'The parameter is null or undefined'),
    new TestCase(func, null, 'The parameter is null or undefined')
  ];
  if (func.length === 2) {
    testcases.forEach(testcase =&gt; testcase.value.push(1));
  }
  for (const testcase of testcases) {
    expect(testcase.fn).toThrowError(testcase.errMsg);
  }
}

class TestCase {
  constructor (testFn, value, errMsg) {
    this.value = [value];
    this.errMsg = errMsg;
    this.testFn = testFn;
  }
  fn () {
    this.testFn.apply(null, this.value);
  }
}
```