简体   繁体   中英

Trying to shorten redundant Javascript code

This is a working javascript code. However, it looks redundant to me. Is there any way to clean this up?

let text = 'Some search text';

const searchMatch = 
entry.title.toLowerCase().includes(text.toLowerCase()) || 
entry.description.toLowerCase().includes(text.toLowerCase()) || 
entry.keywords.toLowerCase().includes(text.toLowerCase());

return searchMatch;

You could do something like this:

const text = 'Some search text'.toLowerCase();

return [entry.title, entry.description, entry.keywords].some(s => s.toLowerCase().includes(text));

You might use an array and a .some test instead:

const textLower = text.toLowerCase();
return ['title', 'description', 'keywords']
  .map(prop => entry[prop].toLowerCase())
  .some(s => s.includes(textLower));

If, by chance, entry contains only those properties, then you could use Object.values instead:

return Object.values(entry)
  .map(s => s.toLowerCase())
  .some(s => s.includes(textLower));

You could just use a one-line return statement involving an array composed of entry.description , entry.keywords and entry.title , and then using Array.prototype.some() to return a Boolean ( true / false ) value depending on whether any of the tests pass:

return [entry.description, entry.keywords, entry.title].some(string => string.toLowerCase().includes('Some search text'.toLowerCase());

Here's essentially a breakdown of each part:

[entry.description, entry.keywords, entry.title].some(...)

What this does is makes an anonymous array composed of entry.description , entry.keywords , and entry.title (the order does not matter) and iterates through it with the Array.prototype.some() method. According to the MDN page , .some() :

The some() method tests whether at least one element in the array passes the test implemented by the provided function.

Essentially iterates through each element, and depending on the callback from the provided function, and provides a Boolean value ( true if at least one element in the array passes the test, false if no elements pass the test).

string => string.toLowerCase().includes('Some search text'.toLowerCase())

This is the anonymous function contained within the .some() method, and it takes a single parameter string . Then it returns a Boolean value, depending on the outcome of the .includes() method. The .includes() method returns another Boolean value, depending on whether the lowercased string contains the lowercased 'Some search text' . It's a mouthful, but in a nutshell, the line of code above reads:

If string in lowercased form includes 'Some search text' in lowercased form, return true - otherwise, return false .

Hopefully this helps you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM