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)))) ![]@FieldType(std.meta.Elem(@TypeOf(slice)), @tagName(field)) {
6 const newslice = try allocator.alloc(@FieldType(std.meta.Elem(@TypeOf(slice)), @tagName(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}