在JavaScript/TypeScript中实现IEnumerable

the*_*tor 6 javascript c# ienumerable typescript

我正在尝试yield用JavaScript/TypeScript 实现C#关键字(无关紧要):例如,我想实现代码:

//using System.Collections;  
//using System.Diagnostics; 
public static void Process()
{
    // Display powers of 2 up to the exponent of 8:  
    foreach (int number in Power(2, 8))
    {
        Debug.Write(number.ToString() + " ");
    }
    // Output: 2 4 8 16 32 64 128 256
}


public static IEnumerable Power(int baseNumber, int highExponent)
{
    int result = 1;

    for (int counter = 1; counter <= highExponent; counter++)
    {
        result = result * baseNumber;
        yield return result;
    }
}
Run Code Online (Sandbox Code Playgroud)

在JavaScript中.

最终目标是在JavaScript中使用我在stackoverflow上提出的另一个问题来实现一个用C#编写的函数:

public static IEnumerable<string> SplitByCharacterType(string input)
{
    if (String.IsNullOrEmpty(input))
        throw new ArgumentNullException(nameof(input));

    StringBuilder segment = new StringBuilder();
    segment.Append(input[0]);
    var current = Char.GetUnicodeCategory(input[0]);

    for (int i = 1; i < input.Length; i++)
    {
        var next = Char.GetUnicodeCategory(input[i]);
        if (next == current)
        {
            segment.Append(input[i]);
        }
        else
        {
            yield return segment.ToString();
            segment.Clear();
            segment.Append(input[i]);
            current = next;
        }
    }
    yield return segment.ToString();
}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Rya*_*ugh 6

我不认为有一种合理的方法可以在for循环的上下文中完成这项工作,该循环在"下一步"操作期间保留了惰性求值的C#语义.但是,您可以使用闭包来合理地模拟这种情况.

(TypeScript代码):

function getPowers(base: number, maxExponent: number) {
    var currentExponent = 1;
    return function() {
        if(currentExponent > maxExponent) {
            return undefined;
        } else {
            return Math.pow(base, currentExponent++);
        }
    }
}

// Simple test
var p = getPowers(2, 8);
var n: number;
while((n = p()) !== undefined) {
    console.log(n);
}

// Demonstrate that multiple instances work
var p2 = getPowers(2, 3);
var p3 = getPowers(3, 3);
while(true) {
    var n2 = p2();
    var n3 = p3();
    if((n2 || n3) === undefined) break;

    console.log(n2 + ", " + n3);
}
Run Code Online (Sandbox Code Playgroud)