Question

CoffeeScript:

list = [[0, 0], [0, 1], [1, 0]]
console.log [0, 0] in list     #false
console.log [1, 0] in list     #false
console.log [0, 1] in list     #false
console.log [1, 1] in list     #false

Python:

>>> lst = [[0, 0], [0, 1], [1, 0]]
>>> [0, 0] in lst
True
>>> [1, 0] in lst
True
>>> [0, 1] in lst
True
>>> [1, 1] in lst
False

How would I make CoffeeScript replicate Python's 'in' for this?

Was it helpful?

Solution

It does work the way you want actually, but its by reference:

item1 = [0, 0]
item2 = [0, 1]
item3 = [1, 0]
item4 = [1, 1]

list  = [item1, item2, item3]

console.log item1 in list # true
console.log item2 in list # true 
console.log item3 in list # true
console.log item4 in list # false

To make it work by deep check instead of reference, you would have to fork the coffee-script compiler, add this feature to the coffee-script language, then submit a pull request, convince the gatekeepers that this is a good feature and hope they merge it in.

list = [[0, 0], [0, 1], [1, 0]]
contains = (lst, compare) ->
  ret = true for l in lst when l[0] is compare[0] and l[1] is compare[1]       
  return Boolean ret

console.log contains list, [0, 0] # true
console.log contains list, [1, 0] # true
console.log contains list, [0, 1] # true
console.log contains list, [1, 1] # false

OTHER TIPS

Coffeescript translates item1 in list to (ignoring the patch that handles browsers without indexOf):

list.indexOf(item1) >= 0;

So it is constrained by how Javascript codes indexOf. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

indexOf compares searchElement to elements of the Array using strict equality (the same method used by the ===, or triple-equals, operator).

This would be, roughly, equivalent to a Python list search that uses is to compare item1 and list[i]. Compare these 2 python statements

[[0,1] is l for l in alist]
[alist[1] is l for l in alist]

To write a Coffeescript (or Javascript) that behaves the same as Python, you need a way of comparing two arrays. Compare

[0,1]==[0,1]

in all 3 languages. It is true only Python.

underscore implements a deep comparison:

isEqual_.isEqual(object, other) Performs an optimized deep comparison between the two objects, to determine if they should be considered equal.

Using that I can define a function which returns the item if found, undefined if not

ud = require 'underscore'
myin = (list, item)->
  ud.find(list,(x)->
    ud.isEqual(item,x))
myin(list,[0,0])
    # [ 0, 0 ]
myin(list,[0,3])
    # undefined
myin(list,[0,1])?
    # true
myin(list,[2,2])?
    # false
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top