如果渴望評估是好的,你可以將你的根收集到一個數組中,並使用roots.filter(isinvalid)
來取出無效的值;那麼只需使用結果數組中的第一項。
如果您需要延遲計算,可以概括成懶洋洋地評估一個數組,直到一個非空的結果如下功能的功能,這是發現:
// call fn on items in arr until fn returns non-null
// returns [item, result]
// if result===false, no true value was returned
function firstNotNull(fn, arr) {
var i, length, item, result=null;
for (i = 0, length=arr.length; i < length; i++) {
item = arr[i];
result = fn(item);
if (result!==null) {
break;
}
}
return [item, result];
}
function rootComputations(root) {
var computationResult = null;
if (root==1) {
computationResult = 1;
}
return computationResult;
}
function computeRoots() {
return [0,1];
}
function foo() {
var velocity, roots, root, result, computations;
for (velocity = 0; velocity < 100; velocity++) {
roots = computeRoots();
computations = firstNotNull(rootComputations, roots);
console.log(computations);
root = computations[0];
result = computations[1];
}
}
foo();
可以概括firstNotNull()
更進一步:
// call fn on items in arr until cond(fn(item)) returns true
// returns [item, fn(item)], or null if unsatisfied
function firstSatisfying(cond, fn, arr) {
var i, length, item, fnitem, result=null;
for (i = 0, length=arr.length; i < length; i++) {
item = arr[i];
fnitem = fn(item);
if (cond(fnitem)) {
result = [item, fnitem];
break;
}
}
return result;
}
var firstNotNull = firstSatisfying.bind(null, function(item){return item!==null;});
您現在有一個通用函數,用於獲取滿足所需條件的列表中的第一個。
的ECMAScript 5中添加了許多方法,這使得渴望功能應用在陣列更容易,但JavaScript並沒有任何本地設施懶評價。如果這是你認爲你經常需要的東西,考慮使用stream.js,它提供了一個「流」數據類型和部分應用的方法。使用stream.js,你的邏輯是這樣的:
// rootStream should be a function which returns a Stream
// It should construct a stream with the first root produced
// and a function that returns the remaining roots.
// Since I don't know how you get your roots, I'll use a stupid example:
function rootStream() {
return new Stream(0, function(){
return new Stream(1);
});
}
function isvalid(root) {
return root===1;
}
Stream.range(0,100)
.walk(function(v){
//v doesn't seem to be used?
var firstvalid = rootStream().filter(isvalid).head();
console.log(firstvalid);
});
有一個權衡的意義,首先是共同計算,所以你總是做兩次工作,而後者則只能在重新計算首先是「無效」。對? –
@JaredFarrish - 大概你可以在'for'循環中測試一些條件,並決定是否繼續進行額外的迭代 - 如果完成了,就會退出'for'循環。 – jfriend00
@ jfriend00感謝您的輸入,我認爲#1是我正在尋找的。此外,爲了清晰起見,更新了我的代碼片段 –