authorgravatar for hello@nektro.netMeghan Denny <hello@nektro.net> 2025-02-05 03:12:41 -08:00
committergravatar for hello@nektro.netMeghan Denny <hello@nektro.net> 2025-02-05 03:12:41 -08:00
log21ea23271a2e10f81cd993d4065d7a5a846e1099
tree6bf6777278717bb1c405120e5667e5719c526fc7
parent10347e86f82360e2b31d998fd2233bfb8aee6b69

add lessThanBy


3 files changed, 22 insertions(+), 5 deletions(-)

src/lessThanBy.zig created+20
...@@ -0,0 +1,20 @@
1const std = @import("std");
2const string = []const u8;
3const extras = @import("./lib.zig");
4
5pub fn lessThanBy(comptime T: type, comptime field: std.meta.FieldEnum(T)) fn (void, T, T) bool {
6 const S = struct {
7 pub fn lessThan(_: void, lhs: T, rhs: T) bool {
8 return @field(lhs, @tagName(field)) < @field(rhs, @tagName(field));
9 }
10 };
11 return S.lessThan;
12}
13
14test {
15 const S = struct { x: u32 };
16 const l = lessThanBy(S, .x);
17 try std.testing.expect(l({}, .{ .x = 19 }, .{ .x = 53 }));
18 try std.testing.expect(!l({}, .{ .x = 44 }, .{ .x = 44 }));
19 try std.testing.expect(!l({}, .{ .x = 89 }, .{ .x = 26 }));
20}
src/lib.zig+1
...@@ -101,3 +101,4 @@ pub usingnamespace @import("./isSlice.zig");...@@ -101,3 +101,4 @@ pub usingnamespace @import("./isSlice.zig");
101pub usingnamespace @import("./matchesNone.zig");101pub usingnamespace @import("./matchesNone.zig");
102pub usingnamespace @import("./indexOfSlice.zig");102pub usingnamespace @import("./indexOfSlice.zig");
103pub usingnamespace @import("./mapBy.zig");103pub usingnamespace @import("./mapBy.zig");
104pub usingnamespace @import("./lessThanBy.zig");
src/sortBy.zig+1-5
...@@ -3,11 +3,7 @@ const string = []const u8;...@@ -3,11 +3,7 @@ const string = []const u8;
3const extras = @import("./lib.zig");3const extras = @import("./lib.zig");
44
5pub fn sortBy(comptime T: type, items: []T, comptime field: std.meta.FieldEnum(T)) void {5pub fn sortBy(comptime T: type, items: []T, comptime field: std.meta.FieldEnum(T)) void {
6 std.mem.sort(T, items, {}, struct {6 std.mem.sort(T, items, {}, extras.lessThanBy(T, field));
7 fn f(_: void, lhs: T, rhs: T) bool {
8 return @field(lhs, @tagName(field)) < @field(rhs, @tagName(field));
9 }
10 }.f);
11}7}
128
13test {9test {