From b81a5325ef21e37bb9aa46b23cf8bc445d283708 Mon Sep 17 00:00:00 2001 From: Delyan Angelov Date: Wed, 27 Sep 2023 11:26:05 +0300 Subject: [PATCH] arrays: add arrays.each, arrays.each_indexed, and tests for them --- vlib/arrays/arrays.v | 16 +++++++++++++++ vlib/arrays/arrays_test.v | 43 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) diff --git a/vlib/arrays/arrays.v b/vlib/arrays/arrays.v index d128640aa6..47e95b5929 100644 --- a/vlib/arrays/arrays.v +++ b/vlib/arrays/arrays.v @@ -11,6 +11,7 @@ import strings // - window - get snapshots of the window of the given size sliding along array with the given step, where each snapshot is an array // - group - merge two arrays by interleaving e.g. arrays.group([1,3,5], [2,4,6]) => [[1,2],[3,4],[5,6]] // - flatten - reduce dimensionality of array by one. e.g. arrays.flatten([[1,2],[3,4],[5,6]]) => [1,2,3,4,5,6] +// - each - call a callback fn, for each element of the array, similar to a.map(), but unlike it, the callback should not return anything // min returns the minimum value in the array // Example: arrays.min([1, 2, 3, 0, 9])! // => 0 @@ -743,3 +744,18 @@ pub fn partition[T](array []T, predicate fn (elem T) bool) ([]T, []T) { } return matching, non_matching } + +// each calls the callback fn `cb`, for each element of the given array `a` +pub fn each[T](a []T, cb fn (elem T)) { + for item in a { + cb(item) + } +} + +// each_indexed calls the callback fn `cb`, for each element of the given array `a`, +// passing it both the index of the current element, and the element itself +pub fn each_indexed[T](a []T, cb fn (i int, e T)) { + for idx, item in a { + cb(idx, item) + } +} diff --git a/vlib/arrays/arrays_test.v b/vlib/arrays/arrays_test.v index 55e7edd947..9011567af3 100644 --- a/vlib/arrays/arrays_test.v +++ b/vlib/arrays/arrays_test.v @@ -498,3 +498,46 @@ fn test_partition() { assert lower2.len == 0 assert upper2.len == 8 } + +fn test_each() { + a := [99, 1, 2, 3, 4, 5, 6, 7, 8, 1001] + mut control_sum := 0 + for x in a { + control_sum += x + } + // + each(a, fn (x int) { + println(x) + }) + mut sum := 0 + mut psum := &sum + each(a, fn [mut psum] (x int) { + unsafe { + *psum += x + } + }) + assert control_sum == sum +} + +fn test_each_indexed() { + a := [99, 1, 2, 3, 4, 5, 6, 7, 8, 1001] + mut control_sum := 0 + f := fn (idx int, x int) int { + return (idx + 1) * 1000_000 + x + } + for idx, x in a { + control_sum += f(idx, x) + } + // + each_indexed(a, fn (idx int, x int) { + println('idx: ${idx}, x: ${x}') + }) + mut sum := 0 + mut psum := &sum + each_indexed(a, fn [mut psum, f] (idx int, x int) { + unsafe { + *psum += f(idx, x) + } + }) + assert control_sum == sum +}