Skip to content

Instantly share code, notes, and snippets.

@brianmichel
Created May 12, 2023 12:45
Show Gist options
  • Select an option

  • Save brianmichel/a5e7d953f41376519d3b1cfecd3616a5 to your computer and use it in GitHub Desktop.

Select an option

Save brianmichel/a5e7d953f41376519d3b1cfecd3616a5 to your computer and use it in GitHub Desktop.

Revisions

  1. brianmichel created this gist May 12, 2023.
    48 changes: 48 additions & 0 deletions chartd.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,48 @@
    import Foundation

    let b62 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

    func encode(data: [Double], min: Double, max: Double) -> String {
    let r = max - min
    var bs = [Character](repeating: b62.first!, count: data.count)
    if r == 0 {
    for i in 0..<data.count {
    bs[i] = b62.first!
    }
    return String(bs)
    }
    let enclen = Double(b62.count - 1)
    for (i, y) in data.enumerated() {
    let index = Int(enclen * (y - min) / r)
    if index >= 0 && index < b62.count {
    bs[i] = b62[b62.index(b62.startIndex, offsetBy: index)]
    } else {
    bs[i] = b62.first!
    }
    }
    return String(bs)
    }
    // http://chartd.co/a.svg?w=580&h=180&d0=caaageehox301yusuurywwqmjdghhhjmrt0yywwuqrs2yslkgfahnomqux666zzvttv0wsmkgdbhmnlrsz6795420xtvtrnjgdadkopqqv256520zxsssokfdZZbeffjltwzzzxussuywrmgbYWaeefjmu100ywsqqrvuoidb&ymin=0&ymax=160000000&t=1+week+@+1+hour&step=1"

    let data0 = [1.0, 0.99, 0.9869, 0.95, 0.88]
    let data1 = [0.0, 0.01, 0.02, 0.05, 0.12]
    let encoded0 = encode(data: data0, min: 0.0, max: 1.0)
    let encoded1 = encode(data: data1, min: 0.0, max: 1.0)
    let minTime = Date().timeIntervalSince1970 - Double(data0.count * 24 * 60 * 60)
    let maxTime = Date().timeIntervalSince1970

    var components = URLComponents(string: "https://chartd.co/a.svg")
    components?.queryItems = [
    .init(name: "w", value: "600"),
    .init(name: "h", value: "200"),
    .init(name: "d0", value: encoded0),
    .init(name: "d1", value: encoded1),
    .init(name: "ymin", value: "0.0"),
    .init(name: "ymax", value: "1.0"),
    .init(name: "step", value: "0"),
    .init(name: "xmin", value: "\(Int(minTime))"),
    .init(name: "xmax", value: "\(Int(maxTime))"),
    ]

    print(components!.url)