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

CoffeeScript uses arrays to exchange variables


May 09, 2021 CoffeeScript


Table of contents


Use arrays to exchange variables

Problem

You want to exchange variables through arrays.

Solution

Deconstructed assignment syntax using CoffeeScript:

a = 1
b = 3

[a, b] = [b, a]

a
# => 3

b
# => 1

Discuss

Deconstructing assignments can implement the exchange of variable values without relying on temporary variables.

This syntax is particularly suitable for those who only want to iterate on the shortest array when traversing the array:

ray1 = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
ray2 = [ 5, 9, 14, 20 ]

intersection = (a, b) ->
  [a, b] = [b, a] if a.length > b.length
  value for value in a when value in b

intersection ray1, ray2
# => [ 5, 9 ]

intersection ray2, ray1
# => [ 5, 9 ]