2011-12-21 130 views

回答

12

找到一種方法來檢查使用此CoffeeScript chapter兩個數組之間的交集。 CoffeeScript看起來非常棒。

如果在元素相交後得到的數組至少包含一個項目,那麼兩個數組都有公共元素。

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

x = ["hello", "two", "three"] 
y = ["hello"] 

intersection x, y // ["hello"] 

試試吧here

+0

嗯,我感到相當的第一行迷惑,和CoffeeScript的的核心優勢之一是應該是增加JS的清晰度和可讀性,對吧?也許這是一些聰明但複雜的代碼,只有在@alessioalex提供的更清晰的代碼效率更高時才能使用。 – GregL 2011-12-21 05:57:31

+0

@GregL - 你的意思是這條線 - 'intersection =(a,b) - >'? – Anurag 2011-12-21 06:53:11

+0

對不起,我的意思是第2行,這是交集函數的第一行。到目前爲止,我已經學會了足夠的CS語法來讀取第一行。 :-)更多的是我不明白這條線是如何工作的。 – GregL 2011-12-21 07:36:30

1

我做了一個功能IS_IN,看一下我的例子:

array1 = ["hello","two","three"] 
array2 = ["hello"] 

is_in = (array1, array2) -> 
    for i in array2 
    for j in array1 
     if i is j then return true 

console.log is_in(array1, array2) 

Test here

在看看交叉口例子,我可以以另一種方式實現這一目標:

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

array1 = ["hello","two","three"] 
array2 = ["hello"] 

console.log intersection(array1, array2) 

Test here

+0

前者更容易理解 - 如果有人想爲此創建一個jsPerf.com測試,看看您發佈的交叉碼是否有任何好處,我會很好奇。 – GregL 2011-12-21 05:59:46

+0

你可以自己創建一個jsPerf測試。點擊兩個'Test here'鏈接,然後從那裏獲取已編譯的JavaScript代碼。之後,創建一個jsPerf與2例。 – alessioalex 2011-12-21 08:49:53

1

你可以試試:

(true for value in array1 when value in array2).length > 0 
2
contains = (item for item in array2 when item in array1) 

(扭轉陣列顯示array1雙項)

7

想我應該把我自己的CoffeeScript的一行瘋狂:-P

true in (val in array1 for val in array2) 
1

以防萬一有人來到這裏,並尋找差異,而不是相交

difference = (val for val in array1 when val not in array2) 

這會給你一個數組中陣列1的所有值(差異但不是在數組2

相關問題