2015-04-17 57 views
0

我試圖找到最好的方式來完成一個數組循環,這應該返回一個值,一旦「if」語句匹配。coffeescript:打破if語句

我有兩個字符串,並試圖遍歷他們的字符並比較它們(對於排序函數)。一旦滿足比較條件,我需要重複打破。

最理想的,這樣的事情:

a = 'here is one' 
b = 'here is two' 
if a.charCodeAt(i) < b.charCodeAt(i) then -1 else 1 for i in [0...a.length] when a.charCodeAt(i) != b.charCodeAt(i) 

但是,這轉化爲:

if (a.charCodeAt(i) < b.charCodeAt(i)) { 
    return -1; 
} else { 
    _results = []; 
    for (i = _i = 0, _ref = a.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) { 
    if (a.charCodeAt(i) !== b.charCodeAt(i)) { 
     _results.push(1); 
    } 
    } 
    return _results; 
} 

的另一種嘗試:

pos = (if a.charCodeAt(i) < b.charCodeAt(i) then -1 else 1) for i in [0...a.length] when a.charCodeAt(i) != b.charCodeAt(i) 

翻譯爲:

_results = []; 
for (i = _i = 0, _ref = a.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) { 
    if (a.charCodeAt(i) !== b.charCodeAt(i)) { 
    _results.push(pos = (a.charCodeAt(i) < b.charCodeAt(i) ? -1 : 1)); 
    } 
} 
return _results; 

這是我目前的解決方法:

a = 'here is one' 
b = 'here is two' 
return (for i in [0...a.length] 
    do -> 
    if a.charCodeAt(i) < b.charCodeAt(i) then -1 else 1 
)[0] 

翻譯爲:

return ((function() { 
    var _i, _ref, _results; 
    _results = []; 
    for (index = _i = 0, _ref = a['dep'].length; 0 <= _ref ? _i < _ref : _i > _ref; index = 0 <= _ref ? ++_i : --_i) { 
    _results.push((function() { 
     if (a['dep'].charCodeAt(index) < b['dep'].charCodeAt(index)) { 
     return -1; 
     } else { 
     return 1; 
     } 
    })()); 
    } 
    return _results; 
})())[0]; 

做工作......但效果並不理想。 想法?

+0

呃...''foo'.localeCompare'bar'' ...!? – deceze

回答

2

只需使用多條線,無論如何它都使其更具可讀性。

a = 'here is one' 
b = 'here is two' 
[x] = for i in [0...a.length] when a.charCodeAt(i) != b.charCodeAt(i) 
    if a.charCodeAt(i) < b.charCodeAt(i) then -1 else 1