| 1 | const expectEqual = @import("std").testing.expectEqual; |
| 2 | |
| 3 | const CmdFn = struct { |
| 4 | name: []const u8, |
| 5 | func: fn (i32) i32, |
| 6 | }; |
| 7 | |
| 8 | const cmd_fns = [_]CmdFn{ |
| 9 | CmdFn{ .name = "one", .func = one }, |
| 10 | CmdFn{ .name = "two", .func = two }, |
| 11 | CmdFn{ .name = "three", .func = three }, |
| 12 | }; |
| 13 | fn one(value: i32) i32 { |
| 14 | return value + 1; |
| 15 | } |
| 16 | fn two(value: i32) i32 { |
| 17 | return value + 2; |
| 18 | } |
| 19 | fn three(value: i32) i32 { |
| 20 | return value + 3; |
| 21 | } |
| 22 | |
| 23 | fn performFn(comptime prefix_char: u8, start_value: i32) i32 { |
| 24 | var result: i32 = start_value; |
| 25 | comptime var i = 0; |
| 26 | inline while (i < cmd_fns.len) : (i += 1) { |
| 27 | if (cmd_fns[i].name[0] == prefix_char) { |
| 28 | result = cmd_fns[i].func(result); |
| 29 | } |
| 30 | } |
| 31 | return result; |
| 32 | } |
| 33 | |
| 34 | test "perform fn" { |
| 35 | try expectEqual(6, performFn('t', 1)); |
| 36 | try expectEqual(1, performFn('o', 0)); |
| 37 | try expectEqual(99, performFn('w', 99)); |
| 38 | } |
| 39 | |
| 40 | // test |