SPB Git

Repository Public

Support.swift 2.6 KB 69 lines swift

1import Foundation2import Testing3import SheetCore4import SheetUI5import FunctionsNumeric6import FunctionsLookup7import AnalysisKit8@testable import FinanceStudio910let en = Locale(identifier: "en_US")1112func registerFunctions() {13    NumericFunctions.register()14    FinancialFunctions.register()15}1617@MainActor func makeSession(_ rows: [[String]] = [], sheets: [String] = ["Data"]) -> WorkbookSession {18    registerFunctions()19    let session = WorkbookSession(workbook: Workbook(sheetNames: sheets), locale: en)20    session.perform("Fill") { e in21        for (r, row) in rows.enumerated() { for (c, text) in row.enumerated() where !text.isEmpty {22            try? e.setInput(sheet: 0, row: r, col: c, text, parser: session.parser)23        } }24    }25    session.engine.clearUndoHistory()26    return session27}2829/// Runs a tool with its default form values modified by `configure`.30@MainActor func run(_ tool: ToolDescriptor, session: WorkbookSession, _ configure: (inout FormValues) -> Void = { _ in }) throws -> ToolResult {31    var v = FormValues(defaults: tool.fields)32    configure(&v)33    return try tool.run(try ToolInputResolver.resolve(tool, values: v, session: session))34}3536extension ToolResult {37    /// Number in the second column of the row whose first cell equals (or starts with) `label`, in any table.38    func number(_ label: String, column: Int = 1) -> Double? {39        for t in tables { for row in t.rows {40            if case .text(let s) = row[0], s == label || s.hasPrefix(label + " —"), column < row.count, case .number(let x) = row[column] { return x }41        } }42        return nil43    }44    func metric(_ label: String) -> Double? {45        for b in blocks { if case .metrics(let ms) = b, let m = ms.first(where: { $0.label == label }), case .number(let x) = m.value { return x } }46        return nil47    }48    var warnings: [String] { blocks.flatMap { b -> [String] in if case .text(let t) = b, t.kind == .warning { t.lines } else { [] } } }49    func action(_ id: String) -> ResultAction? { actions.first { $0.id == id } }50}5152func snapshot(_ wb: Workbook) -> [String] {53    var out = [String]()54    for s in wb.sheets {55        var cells = [String]()56        s.cells.forEachAll { r, c, cell in57            if cell.hasContent || cell.style != 0 { cells.append("\(r),\(c)=\(cell.computed)|\(cell.formula != nil)|\(wb.styles[cell.style].hashValue)") }58        }59        out.append(s.name + ":" + cells.sorted().joined(separator: ";"))60    }61    out.append("names:" + wb.names.keys.sorted().joined(separator: ","))62    return out63}6465func close(_ a: Double?, _ b: Double, _ tol: Double = 1e-9) -> Bool {66    guard let a else { return false }67    return abs(a - b) <= tol * max(1, abs(b))68}69
Files main
Menu

Theme