authorgravatar for hello@nektro.netMeghan Denny <hello@nektro.net> 2025-02-05 03:08:35 -08:00
committergravatar for hello@nektro.netMeghan Denny <hello@nektro.net> 2025-02-05 03:08:35 -08:00
log10347e86f82360e2b31d998fd2233bfb8aee6b69
tree034fa819e7538a6705d115d60ffab54cca0da0f2
parent671e2bd52fe822c66aa002f51d00c1919f20c61d

add mapBy


2 files changed, 20 insertions(+), 0 deletions(-)

src/lib.zig+1
...@@ -100,3 +100,4 @@ pub usingnamespace @import("./isIndexable.zig");...@@ -100,3 +100,4 @@ pub usingnamespace @import("./isIndexable.zig");
100pub usingnamespace @import("./isSlice.zig");100pub 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");
src/mapBy.zig created+19
...@@ -0,0 +1,19 @@
1const std = @import("std");
2const string = []const u8;
3const extras = @import("./lib.zig");
4
5pub fn mapBy(allocator: std.mem.Allocator, slice: anytype, comptime field: std.meta.FieldEnum(std.meta.Elem(@TypeOf(slice)))) ![]std.meta.FieldType(std.meta.Elem(@TypeOf(slice)), field) {
6 const newslice = try allocator.alloc(std.meta.FieldType(std.meta.Elem(@TypeOf(slice)), field), slice.len);
7 for (newslice, slice) |*i, j| i.* = @field(j, @tagName(field));
8 return newslice;
9}
10
11test {
12 const alloc = std.testing.allocator;
13 const S = struct { x: u32 };
14 const original: []const S = &.{ .{ .x = 53 }, .{ .x = 89 }, .{ .x = 19 }, .{ .x = 44 }, .{ .x = 29 } };
15 const expected: []const u32 = &.{ 53, 89, 19, 44, 29 };
16 const mapped = try mapBy(alloc, original, .x);
17 defer alloc.free(mapped);
18 try std.testing.expectEqualSlices(u32, expected, mapped);
19}