Created
May 12, 2023 12:45
-
-
Save brianmichel/a5e7d953f41376519d3b1cfecd3616a5 to your computer and use it in GitHub Desktop.
Generate a chartd chart with Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment