Skip to content

Commit 1373fd8

Browse files
committed
Added WithRandomOffset helper method
1 parent 06a2925 commit 1373fd8

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
using System.Linq;
2+
using Cleipnir.ResilientFunctions.Helpers;
3+
using Microsoft.VisualStudio.TestTools.UnitTesting;
4+
using Shouldly;
5+
6+
namespace Cleipnir.ResilientFunctions.Tests.UtilsTests;
7+
8+
[TestClass]
9+
public class HelpersTests
10+
{
11+
[TestMethod]
12+
public void AllElementsExistsWhenCreateEnumerableWithRandomOffset()
13+
{
14+
var randomOffsetEnumerable = Enumerable.Range(0, count: 10)
15+
.ToList()
16+
.WithRandomOffset();
17+
18+
var set = randomOffsetEnumerable.ToHashSet();
19+
20+
Enumerable
21+
.Range(0, count: 10)
22+
.All(i => set.Contains(i))
23+
.ShouldBeTrue();
24+
}
25+
}

Core/Cleipnir.ResilientFunctions/Helpers/Helpers.cs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,5 +55,16 @@ public static T[] RandomlyPermute<T>(this IEnumerable<T> t)
5555
return arr;
5656
}
5757

58+
public static IEnumerable<T> WithRandomOffset<T>(this IReadOnlyList<T> elms)
59+
{
60+
var offset = Random.Shared.Next(0, elms.Count);
61+
var i = offset;
62+
do
63+
{
64+
yield return elms[i];
65+
i = (i + 1) % elms.Count;
66+
} while (i != offset);
67+
}
68+
5869
internal static string MinifyJson(string json) => Regex.Replace(json, "(\"(?:[^\"\\\\]|\\\\.)*\")|\\s+", "$1");
5970
}

0 commit comments

Comments
 (0)