Problem
I’m having trouble thinking of a good name for the following extension method:
public static IEnumerable<T> TrimOrExpand<T>(this T[] items, int desiredCount)
{
var ratio = (double)items.Length / desiredCount;
for (int i = 0; i < desiredCount; i++)
yield return items[Convert.ToInt32(i * ratio)];
}
The thing I don’t like about this method name is that “Trim” may communicate to the user that it’s cutting off the last x records of the array, when actually it is excluding items at a regular interval throughout the array. Likewise it will also “Expand” the array by repeating items if you specify a count that is larger than items.Length
.
Is there a better technical term for what I’m trying to do? Or is TrimOrExpand
obvious enough to understand what it does?
Solution
Wow. That’s an interesting method. I’ve never seen anything do quite what it does. Kudos. Though for naming, I might call it ContractOrExpand
or InterpolateOrExtrapolate
or something like that. The Trim
does seem to evoke thoughts of string.Trim()
which is totally different. And even SQL’s TRIM()
, for that matter. I feel that that bit of wording implies stuff will be chopped off at the front or back, while your method cuts stuff out at regular intervals (if need be). So, take that for what it’s worth.
On another note, you should be able to replace Convert.ToInt32(i * ratio)
with (int)(i * ratio)
and get the same results without the overhead of a method call. Measure if this could be performance-critical.
I think if you look at the objects within the IEnumerable as a statistical numeric value than you could use the term Normalize. In this case you are “normalizing” your values (objects) to a desired count.
public static IEnumerable<T> NormalizeObjects<T>(this T[] items, int desiredCount)
If you dislike the term Objects you could replace it with Items or even Records depending on what your use case is.
If the only thing you dislike about your current name is “Trim” then you could replace that term with the opposite of Expand, which I would argue is Contract.
public static IEnumerable<T> ExpandOrContract<T>(this T[] items, int desiredCount)
I think either of the above are decent options based on what your method is currently doing.