samedi 2 mars 2019

Dynamically generating multiple conditions inside a Javascript if statement

Inside the .map() function of my React component, I have an if statement which I need to contain multiple conditions separated by the || operator. The problem is, this.state.insights is an array consisting of varying lengths depending on the json data that is pulled from my server.

document.getElementById("adMaskid" + this.props.id).innerHTML = audio_data
    .map((sample, i) => {
        let rectOpacity = 1
        if (i > this.state.insights[0].start && i < this.state.insights[0].end || /
            i > this.state.insights[1].start && i < this.state.insights[1].end) {
            rectOpacity = 1;
        } else {
            rectOpacity = 0;
        };

        let sampleWidth = 100.0 / audio_data.length;
        let sampleHeight = sample * 50.0;

        return `<rect style="transform: scaleY(.9); opacity: ${rectOpacity};"
                x=${sampleWidth * i}
                y=${(25 - sampleHeight)}
                width=${sampleWidth}
                height=${sampleHeight} />`
    )}

I'm at a total loss of how to get over this hurdle. If, for example, the this.state.insights array consisted of 3 values, then how would I go about dynamically creating the if statement to reflect that which would look like -

if (i > this.state.insights[0].start && i < this.state.insights[0].end || /
    i > this.state.insights[1].start && i < this.state.insights[1].end ||
    i > this.state.insights[2].start && i < this.state.insights[2].end ||)

Without having to change a bunch of my underlying code, is there a way to do this? I've read about using eval statements but doing so has inclined me to hope that there is a better, safer solution. Thank you very much for any insight. It is extremely appreciated.

Aucun commentaire:

Enregistrer un commentaire