0

The constructor function of the Interpolation class takes in two arrays. How can I set a restriction so that during object creation the length of these two arrays must be equal.

class Interpolation {
    constructor (x, fx) {
        if ( x instanceof Array && fx instanceof Array ) {
            if ( x.length === fx.length ) {
                this.input = x;
                this.output = fx;
            } else { throw 'Unmatching array' }
        } else throw 'Please pass in array';
    }
}

I tried this and during object creating the source code was also printed on the console like this

C:\NeuralNetwork\interpolation.js:7
                        } else { throw('Invalid Array') }
                                 ^
Invalid Array
Bergi
  • 572,313
  • 128
  • 898
  • 1,281
Aditya
  • 595
  • 1
  • 6
  • 15

1 Answers1

1

like this:

class Interpolation {
    constructor (x, fx) {
        if(!(x instanceof Array)) {
            throw('parameter `x` must be an Array.');
        }

        if(!(fx instanceof Array)) {
            throw('parameter `fx` must be an Array,');
        }

        if(x.length !== fx.length) {
            throw('the length of these two arrays(x, fx) must be equal');
        }

        this.input = x;
        this.output = fx;
    }
}
danny.hu
  • 110
  • 3