两个功能的故事
我有一个函数填充数组到指定的值:
function getNumberArray(maxValue) {
const a = [];
for (let i = 0; i < maxValue; i++) {
a.push(i);
}
return a;
}
Run Code Online (Sandbox Code Playgroud)
和一个类似的生成器函数,而不是产生每个值:
function* getNumberGenerator(maxValue) {
for (let i = 0; i < maxValue; i++) {
yield i;
}
}
Run Code Online (Sandbox Code Playgroud)
测试跑步者
我已经为这两种情况编写了这个测试:
function runTest(testName, numIterations, funcToTest) {
console.log(`Running ${testName}...`);
let dummyCalculation;
const startTime = Date.now();
const initialMemory = process.memoryUsage();
const iterator = funcToTest(numIterations);
for (let val of iterator) {
dummyCalculation = numIterations - val;
}
const finalMemory = …Run Code Online (Sandbox Code Playgroud) 关于如何在Swift中创建生成器(或者在Swift中显然调用它们的迭代器)的指南很少,特别是如果您不熟悉该语言.为什么有这么多的发电机类型AnyIterator和UnfoldSequence?为什么下面的代码不应该从单个Ints或s的数组中产生Int?
func chain(_ segments: Any...) -> AnyIterator<Int>{
return AnyIterator<Int> {
for segment in segments {
switch segment {
case let segment as Int:
return segment
case let segment as [Int]:
for i in segment {
return i
}
default:
return nil
}
}
return nil
}
}
let G = chain(array1, 42, array2)
while let g = G.next() {
print(g)
}
Run Code Online (Sandbox Code Playgroud)
我理解它的方式,AnyIterator应该采取{}s中的闭包并将其转换.next()为返回的生成器中的方法,但它似乎不起作用.或者我应该UnfoldSequence像 …