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

CoffeeScript summarizes the array


May 09, 2021 CoffeeScript


Table of contents


Summarize the array

Problem

You have an array of objects that you want to summarize into a value, similar to the reduce() and the reduceRight() in Ruby.

Solution

You can use an anonymous function that includes Array's reduce() and reduceRight() methods to keep the code clear and understandable. The generalization here may be as simple as applying the plus operator to numeric values and strings.

[1,2,3,4].reduce (x,y) -> x + y
# => 10

["words", "of", "bunch", "A"].reduceRight (x, y) -> x + " " + y
# => 'A bunch of words'

Alternatively, it might be more complex, such as clustering elements in a list into a composite object.

people =
    { name: 'alec', age: 10 }
    { name: 'bert', age: 16 }
    { name: 'chad', age: 17 }

people.reduce (x, y) ->
    x[y.name]= y.age
    x
, {}
# => { alec: 10, bert: 16, chad: 17 }

Discuss

Javascript 1.8 introduces reduce and reduceRight, while Coffeescript provides a simple and natural expression syntax for anonymous functions. Together, you can combine the items of the collection into the results of the combination.