On 09/06/2019 01:02 PM, Bob4 wrote:

> I feel like it's wrong to rewrite identical functions over and over.

Enter templates. :)

auto clamp(T)(T value, T mini, T maxi) {
  if (value >= maxi) {
    return maxi;
  }
  if (value <= mini) {
    return mini;
  }
  return value;
}

unittest {
  assert(clamp("k", "d", "y") == "k");
  assert(clamp(42, 10, 20) == 20);
  assert(clamp(0.5, 1.5, 1_000) == 1.5);
}

void main() {
}

You can improve the function with template constraints.

Ali

Reply via email to