Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

CoffeeScript detects each element


May 09, 2021 CoffeeScript


Table of contents


Detect each element

Problem

You want to be able to detect each element in the array under certain circumstances.

Solution

Using Aray.every (ECMAScript 5):

evens = (x for x in [0..10] by 2)

evens.every (x)-> x % 2 == 0
# => true

Array.every was added to Mozilla's Javascript 1.6, ECMAScript 5 standard. I f your browser supports it, but still can't implement EC5, check the .all from underscore .js (http://documentcloud.github.io/underscore/).

For a real example, suppose you have a multi-choice list, as follows:

<select multiple id="my-select-list">
  <option>1</option>
  <option>2</option>
  <option>Red Car</option>
  <option>Blue Car</option>
</select>

Now you want to verify that the user has selected only the numbers. Let's take advantage of array.every :

validateNumeric = (item)->
  parseFloat(item) == parseInt(item) && !isNaN(item)

values = $("#my-select-list").val()

values.every validateNumeric

Discuss

This is similar to the array #all in Ruby.