TransWikia.com

Remove duplicated functions inside different if within a function?

Code Review Asked by Menai Ala Eddine - Aladdin on October 27, 2021

I have a function :

function __throwError(func) {
  if (func.length === 1) {
    function passNumber() {
      func(0);
    }
    function passString() {
      func("item");
    }
    function passEmptyArray() {
      func([]);
    }
    function passUndefinedOrNull() {
      func(undefined || null);
    }
    expect(passNumber).toThrowError("The parameter should be an array");
    expect(passString).toThrowError("The parameter should be an array");
    expect(passEmptyArray).toThrowError("The array is empty");
    expect(passUndefinedOrNull).toThrowError("The parameter is null or undefined");
  }
  if (func.length === 2) {
    function passNumber() {
      func(0, 1);
    }
    function passString() {
      func("item", 1);
    }
    function passEmptyArray() {
      func([], 1);
    }
    function passUndefinedOrNull() {
      func(undefined || null, 1);
    }
    expect(passNumber).toThrowError("The parameter should be an array");
    expect(passString).toThrowError("The parameter should be an array");
    expect(passEmptyArray).toThrowError("The array is empty");
    expect(passUndefinedOrNull).toThrowError("The parameter is null or undefined");
  }
}

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 ?

One Answer

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 => 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);
  }
}
```

Answered by Zmen Hu on October 27, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP