From 254da517d987ff81a97c064f12db8dfe6c062202 Mon Sep 17 00:00:00 2001 From: Vincent Esche Date: Wed, 2 Oct 2019 01:29:12 +0200 Subject: [PATCH] Added closure-based initializer function for Vector and corresponding unit test --- Sources/Surge/Linear Algebra/Vector.swift | 11 +++++++++++ Tests/SurgeTests/VectorTests.swift | 23 +++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/Sources/Surge/Linear Algebra/Vector.swift b/Sources/Surge/Linear Algebra/Vector.swift index caa7db1..f214dd7 100644 --- a/Sources/Surge/Linear Algebra/Vector.swift +++ b/Sources/Surge/Linear Algebra/Vector.swift @@ -46,6 +46,17 @@ public struct Vector where Scalar: FloatingPoint, Scalar: ExpressibleByF self.dimensions = scalars.count self.scalars = scalars } + + public init(dimensions: Int, _ closure: (Int) throws -> Scalar) rethrows { + var scalars: [Scalar] = [] + scalars.reserveCapacity(dimensions) + + for index in 0.. = Vector(dimensions: dimensions, repeatedValue: repeatedValue) + + let expected: Vector = [42, 42, 42, 42, 42] + + XCTAssertEqual(actual, expected) + } + func test_init() { typealias Scalar = Double @@ -36,6 +49,16 @@ class VectorTests: XCTestCase { XCTAssertEqual(lhs.scalars, values) } + func test_init_dimensions_closure() { + typealias Scalar = Double + + let dimensions = 5 + let actual: Vector = Vector(dimensions: dimensions) { Scalar($0) } + let expected: Vector = [0, 1, 2, 3, 4] + + XCTAssertEqual(actual, expected) + } + // MARK: - Subscript func test_subscript() {