#!/usr/bin/ruby

# Test scalar context (provided by the unary + operator).

var TimePiece = require('Time::Piece')

var d = TimePiece.strptime("2020-02-02", "%Y-%m-%d")
var a = [d.add(TimePiece.ONE_DAY)]
var b = +d.add(TimePiece.ONE_DAY)

assert_eq(a, [0, 0, 0, 3, 1, 120, 1, 33, 0])
assert_eq(b.strftime("%Y-%m-%d"), "2020-02-03")

var palindates = Enumerator({ |f|
    loop {
        f(d) if d.strftime("%Y%m%d").is_palindrome
        d = +d.add(TimePiece.ONE_DAY)
    }
})

assert_eq(palindates.first(2).map { .strftime("%Y-%m-%d") }, ["2020-02-02", "2021-12-02"])

do {
    func foo(n) {
        (n, n+1, n+2)
    }

    var a =  foo(42)    # first element
    var b = +foo(42)    # last element

    assert_eq(a, 42)
    assert_eq(b, 44)
}

do {
    require('Algorithm::Combinatorics')

    var data = %w(a b c)
    var iter = +%S<Algorithm::Combinatorics>.permutations(data)

    assert_eq(
        gather {
            while (var p = iter.next) {
                take(p)
            }
        },
    data.permutations)

    assert_eq([%S<Algorithm::Combinatorics>.permutations(data)], data.permutations)   # list context
}

do {
    require('Algorithm::Loops')

    var arr1 = %w(a b c)
    var arr2 = %w(x y z)
    var iter = +%S<Algorithm::Loops>.NestedLoops([arr1, arr2])

    assert_eq(
        gather {
            while (var *car = iter.call) {
                take(car.clone)
            }
        },
        [arr1, arr2].cartesian
    )

    assert_eq([%S<Algorithm::Loops>.NestedLoops([arr1, arr2], {|*a| a })], [arr1, arr2].cartesian)  # list context
}

say "** Test passed!"
