What is the best way to create a Scfilter that can effectively filter both string and number values?

Here is some Javascript (coffescript) code:

.filter "scFilter", () ->
  (collection, search) ->
    return collection unless search
    regexp = createAccentRegexp(search)
    doesMatch = (txt) -> (''+txt).match(regexp)
    collection.filter (el) ->
      if typeof el == 'object'
        return true for att, value of el when (typeof(value) === 'string' || typeof(value) === 'number') and doesMatch(value) and att !== '$$hashKey'
      else  
        doesMatch(el)

I am looking to modify the line "return true for att, value of el when typeof(value) is 'string' and doesMatch(value) and att isnt '$$hashKey'" so that it can filter both number and string values.

Answer №1

If you want to improve the readability of your code, consider refining the conditional logic. Here are some alternative ways to express the condition within a loop:

return true for att, value of el when typeof(value) is 'string' and doesMatch(value) and att isnt '$$hashKey'

You could also achieve the same result with the following code:

for att, value of el
  return true if typeof(value) is 'string' and doesMatch(value) and att isnt '$$hashKey'

The syntax

doSomething() for X of/in Y when condition
can be used as a shorthand, but it's best suited for concise functions that fit on a single line.

To make the code more readable, you can skip over unwanted fields like this:

for att, value of el
  # filter out unwanted values
  continue unless typeof(value) is 'string'
  continue if att is '$$hashKey'
  # Check for matching search terms 
  return true if and doesMatch(value) 

Expanding the search to include numbers is straightforward:

for att, value of el
  # filter out unwanted values
  continue unless typeof(value) in ['string', 'number']
  continue if att is '$$hashKey'
  # Check for matching search terms 
  return true if and doesMatch(value) 

For more insights into CoffeeScript idioms and comprehensions, check out the little book of coffeescript, particularly the idioms section.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why is my Navbar defaulting to be located inside the "./components/Index" folder?

https://i.sstatic.net/5v8IZ.pngI recently created a 'Navbar' component inside the 'components' directory and used a separate index file.js to export it to App.js. However, when I try to import it, it ends up inside the 'components/ ...

The triggering of mouse events on 3D spheres in THREE.js does not occur accurately in the specified location

I've taken over a project from someone else and it's actually pretty cool. The goal is to create a dynamic diagram with nodes (spheres) that can be clicked on to reveal related nodes in a new diagram. Right now, I'm focusing on the clickabl ...

Customizing App (directory) elements in next.js 13

Imagine having this directory organization: https://i.stack.imgur.com/Hd5gu.png Is there a method for loading the component from the custom folder instead of the default one in the app folder? In case the custom folder does not have that component, can t ...

Using jQuery, upon the page loading, the script will automatically trigger a

I am attempting to create an HTML file that automatically logs into my bank account. Below is the code I currently have: <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"> ...

What measures can be taken to ensure that the input checkbox is not toggled by accidentally pressing

There's a checkbox input in a dropdown menu at the top of the page that is giving me some trouble. When I select an option by clicking on it, for some reason pressing the spacebar toggles it off and on. Clicking outside once doesn't correct it, I ...

Variations of a particular software package are necessary

My current project requires Expo, React, and React-Native as dependencies. The configuration in the package.jason file looks like this: "main": "node_modules/expo/AppEntry.js", "private": true, "dependencies": { "expo": "^28.0.0", "expo-three": "^ ...

Enabling client-side access to collections without the need for meteor startup

Whenever I define my Meteor collections on the server and attempt to access them in the client without being within any of the predefined Meteor methods such as rendered, events, created, or helpers, I consistently encounter an error stating Meteor colle ...

Maintain the values of the scope when transferring a template within ng-repeat

I have two sets of data displayed on the interface through ng-repeat Within this, I have included ng-include="template.html" <div> <div ng-repeat="item in items1"> <ng-include src="item.template"></ng-include> </div> ...

Executing Javascript within a Robot Framework test case can be achieved by using the Run Keyword

When attempting to run JavaScript and return a value using run keyword if or similar methods, I encounter an error as anticipated. How can I resolve this issue? Below is an example code snippet: Run Keyword If '${COUNTRY}'=='ES' ${inco ...

Guide on implementing a globalThis polyfill within a NextJS application

Having some trouble with the Mantine react component library on older iOS versions. It's throwing a ReferenceError: Can't find variable: globalThis I've looked into polyfills, but I'm struggling to figure out how to integrate it into ...

Manipulating specific elements within a MongoDB document's array using index values in a Node.js environment

Is there a way to increase the value of a specific element in an array within a MongoDB document using Meteor or nodeJS? For example, consider the following document: { "_id" : "4tP6ewe4Z5kwYA3Je", "name" : "chutia", "address" : "shonir akhra ...

Tips for updating views with asynchronous events in an Angular service or factory

My service is designed to receive asynchronous events, such as those from socket.io. I'm looking for a way to update the views each time a new event is triggered. Since the view isn't directly connected to the service, I'm having trouble upd ...

What is the best method for determining the height of a sandboxed iframe?

My website includes an iframe with the sandbox attribute. Users can set the content of this iframe directly through the 'srcdoc' attribute, which raises security concerns. I am trying to find a way to dynamically adjust the height of the iframe ...

The jQuery function triggers in the console upon first click but does not display in the browser. However, it shows up twice in the browser upon

I'm quite puzzled by this issue. In my javascript file, the jQuery functions (including the one located at the end of the page) seem to skip the first click event and respond twice on the second click. I am also utilizing Bootstrap in my project. App ...

jQuery request avoids encountering any 'Access-Control-Allow-Origin error

I am attempting to retrieve content from one website and transfer it to another website. Unfortunately, I keep encountering the error mentioned in the title during my jQuery request. Below is the code I am using: $.ajax({ url: 'destinationURL' ...

Adding an event listener to the built-in arrow buttons on the `<input type=number>` element is a simple way to enhance user interaction

<input type="number" id="test"> I'm trying to figure out how to set an event listener for the two arrow buttons on the right of this number input field. Typically, we can use jQuery like: $("#test").on("cl ...

Transferring data via AJAX technology

My goal is to empower the ability to upload files using AJAX. I attempted to utilize (JavaScript) in this manner: $("input[type='file']").change(function(){ var file = document.getElementById("uploadelement").files[0]; $.ajax ...

Ways to dynamically update the class name of pre-existing elements in React.js

element, I am currently working on a memory game project where I aim to provide visual feedback to the player when they guess the correct or incorrect answer. Instead of just outputting 'CORRECT' or 'WRONG' to the console, I want the ex ...

Unable to set initial values for Select Option in Redux-Form

I have implemented an update form using redux-form, where the form value is initialized using initialValues. For example: <DataEdit initialValues={ Data }/> The form in the DataEdit page looks like this: <Field name="Data.taxTitle" comp ...

Exploring the use of $ in the outcome of a json for jQuery autocomplete functionality

Trying to implement auto complete functionality. Here is the URL I need to read JSON from: http://openscan.addi.dk/2.0/?action=openScan&field=phrase.title&lower=hest&limit=10&outputType=json After receiving the result, I'm attempting ...