Make an ordinal formatting funcrion

I am hungry
This commit is contained in:
mitteneer 2025-04-29 00:38:20 -04:00
parent 78e416eeaf
commit 3345b20f1f
3 changed files with 23 additions and 2 deletions

View file

@ -2,6 +2,7 @@ const std = @import("std");
const jetzig = @import("jetzig"); const jetzig = @import("jetzig");
const jetquery = @import("jetzig").jetquery; const jetquery = @import("jetzig").jetquery;
const dateFmt = @import("../../date_fmt.zig").dateFmt; const dateFmt = @import("../../date_fmt.zig").dateFmt;
const ordinalFmt = @import("../../ordinal_fmt.zig").ordinalFmt;
pub fn index(request: *jetzig.Request) !jetzig.View { pub fn index(request: *jetzig.Request) !jetzig.View {
var root = try request.data(.object); var root = try request.data(.object);
@ -57,7 +58,11 @@ pub fn get(id: []const u8, request: *jetzig.Request) !jetzig.View {
if (try artist_jq_result.postgresql.result.next()) |artist_row| { if (try artist_jq_result.postgresql.result.next()) |artist_row| {
const artist = try artist_row.to(ArtistResult, .{ .dupe = true, .allocator = request.allocator }); const artist = try artist_row.to(ArtistResult, .{ .dupe = true, .allocator = request.allocator });
try root.put("artist", artist); var artist_view = try root.put("artist", .object);
try artist_view.put("name", artist.name);
try artist_view.put("id", artist.id);
try artist_view.put("scrobbles", artist.scrobbles);
try artist_view.put("rank", ordinalFmt(request.allocator, artist.rank));
} }
try artist_jq_result.drain(); try artist_jq_result.drain();

View file

@ -6,7 +6,7 @@
<body> <body>
@partial partials/header @partial partials/header
<h1>{{.artist.name}}</h1> <h1>{{.artist.name}}</h1>
{{.artist.scrobbles}} scrobbles ({{.artist.rank}}th place) {{.artist.scrobbles}} scrobbles ({{.artist.rank}} place)
<br> <br>
First listen: <a href="/songs/{{.first_song_id}}">{{.first_song_name}}</a> ({{.first_song_date}}) First listen: <a href="/songs/{{.first_song_id}}">{{.first_song_name}}</a> ({{.first_song_date}})
<br> <br>

16
src/ordinal_fmt.zig Normal file
View file

@ -0,0 +1,16 @@
const std = @import("std");
//const log = std.math.log10;
pub fn ordinalFmt(allocator: std.mem.Allocator, ord: isize) ![]const u8 {
const buff = try allocator.alloc(u8, 3 + @as(usize, @intFromFloat(@floor(@log10(@as(f64, @floatFromInt(ord)))))));
const ind: []const u8 = switch (@mod(ord, 100)) {
11, 12, 13 => "th",
else => switch (@mod(ord, 10)) {
1 => "st",
2 => "nd",
3 => "rd",
else => "th",
},
};
return std.fmt.bufPrint(buff, "{}{s}", .{ ord, ind });
}