Profanity Filter with ReactJS

2.8k views Asked by At

Consider the following code:

/* eslint-disable array-callback-return */
/* eslint-disable no-unused-expressions */
import React from 'react'
import './App.css';


let swear = [
'arse',
'ass',
'asshole',
'bastard',
'bitch',
'bollocks',
'bugger',
'bullshit',
'crap',
'damn',
'frigger',
]

const App = () => {
  let [count , setCount] = React.useState(0)
  let [approval , setApproval] = React.useState(false)
  let [text , setText] = React.useState('')


  
  const bogusCheck = (text) =>{
    swear.map(word => {
      text.includes(word) === true ? (console.log('Bad word found') ): (console.log('No bad word found')); 
    })
  }

  return (
    <div className="App">
      <h1>Profanity Checker</h1>
      <p>Enter a sentence below and click the button below:</p>
      <textarea cols="30" rows='10' value={text} onChange={e => setText(e.target.value) } />
      <br />
      <button onClick={() => bogusCheck(text)} >Profanity Check</button>
    </div>

  );
}
export default App;

This is supposed to be a profanity filter. The theory is that it takes input from the text area and then uses the .map() and .includes() function to compare.

swear is an array it includes some bad word.

So the map loops over the swear array, picks up each word and see if it is included in the text. If returns true it console logs (Bad word found). If not it logs(No bad word found)

The issue is that when I click the button, it logs 13 times the not required result and then logs once the required result followed by more non required result. See the image below.

What is the turnabout solution for this??

2

There are 2 answers

0
nodir.dev On BEST ANSWER

change the code a bit:

const bogusCheck = (text) =>{
    const foundSwears = swear.filter(word => text.toLowerCase().includes(word.toLowerCase()));
    if(foundSwears.length){
        console.log('Bad word found');
    } else {
        console.log('No bad word found');
    }
})
0
Leandro Melo On

You can use Array.some() so you don't need to iterate until the end of the array if you already found a bad word.

Since a simple loop as filter will check every element even if you already found one, this is ideal for larger data because with that amount of data this will not make any difference.

You could do the following:

const checkForBadWord = word => {
    return swear.some(el => word.toLowerCase().includes(el.toLowerCase()))
}

This function will return a boolean value, true if found a bad work and false if not