Array Utilities

Common array operations: filtering, mapping, searching

zig (0.11) 2025-11-12 array utility functional collections

Description

A collection of utility functions for working with arrays in Zig. Provides common operations like filtering, mapping, and searching.

Features

  • Array filtering
  • Element mapping
  • Linear search
  • Array reversal

Code

RAW
const std = @import("std");pub fn filter(comptime T: type, allocator: std.mem.Allocator, arr: []const T, predicate: fn (T) bool) ![]T {    var result = std.ArrayList(T).init(allocator);    defer result.deinit();        for (arr) |item| {        if (predicate(item)) {            try result.append(item);        }    }        return result.toOwnedSlice();}pub fn map(comptime T: type, comptime U: type, allocator: std.mem.Allocator, arr: []const T, mapper: fn (T) U) ![]U {    var result = try allocator.alloc(U, arr.len);        for (arr, 0..) |item, i| {        result[i] = mapper(item);    }        return result;}pub fn find(comptime T: type, arr: []const T, value: T) ?usize {    for (arr, 0..) |item, i| {        if (item == value) {            return i;        }    }    return null;}pub fn reverse(comptime T: type, arr: []T) void {    var i: usize = 0;    var j: usize = arr.len - 1;        while (i < j) {        const temp = arr[i];        arr[i] = arr[j];        arr[j] = temp;        i += 1;        j -= 1;    }}pub fn contains(comptime T: type, arr: []const T, value: T) bool {    return find(T, arr, value) != null;}
RAW
const std = @import("std");const array_utils = @import("array_utils.zig");pub fn main() !void {    var gpa = std.heap.GeneralPurposeAllocator(.{}){};    defer _ = gpa.deinit();    const allocator = gpa.allocator();        const arr = [_]i32{ 1, 2, 3, 4, 5 };        // Filter even numbers    const filtered = try array_utils.filter(i32, allocator, &arr, isEven);    defer allocator.free(filtered);        // Map to squares    const mapped = try array_utils.map(i32, i32, allocator, &arr, square);    defer allocator.free(mapped);        // Find value    if (array_utils.find(i32, &arr, 3)) |index| {        std.debug.print("Found at index: {}\n", .{index});    }}fn isEven(n: i32) bool {    return n % 2 == 0;}fn square(n: i32) i32 {    return n * n;}

Comments

No comments yet. Be the first to comment!