diff --git a/src/lib.zig b/src/lib.zig index f5881844952bf91c53a2cb4ced03168e2ec597a1..1ff181a17a3da960fe67986f399cb5f341ee4384 100644 --- a/src/lib.zig +++ b/src/lib.zig @@ -100,3 +100,4 @@ pub usingnamespace @import("./isIndexable.zig"); pub usingnamespace @import("./isSlice.zig"); pub usingnamespace @import("./matchesNone.zig"); pub usingnamespace @import("./indexOfSlice.zig"); +pub usingnamespace @import("./mapBy.zig"); diff --git a/src/mapBy.zig b/src/mapBy.zig new file mode 100644 index 0000000000000000000000000000000000000000..3038acd543c3ccfc0b988e7c741d6e7edb455fa5 --- /dev/null +++ b/src/mapBy.zig @@ -0,0 +1,19 @@ +const std = @import("std"); +const string = []const u8; +const extras = @import("./lib.zig"); + +pub 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) { + const newslice = try allocator.alloc(std.meta.FieldType(std.meta.Elem(@TypeOf(slice)), field), slice.len); + for (newslice, slice) |*i, j| i.* = @field(j, @tagName(field)); + return newslice; +} + +test { + const alloc = std.testing.allocator; + const S = struct { x: u32 }; + const original: []const S = &.{ .{ .x = 53 }, .{ .x = 89 }, .{ .x = 19 }, .{ .x = 44 }, .{ .x = 29 } }; + const expected: []const u32 = &.{ 53, 89, 19, 44, 29 }; + const mapped = try mapBy(alloc, original, .x); + defer alloc.free(mapped); + try std.testing.expectEqualSlices(u32, expected, mapped); +}