Skip to content

Instantly share code, notes, and snippets.

@MrBogomips
Last active October 29, 2021 16:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MrBogomips/0ef3439d099979206dffa5eca8a4dd6b to your computer and use it in GitHub Desktop.
Save MrBogomips/0ef3439d099979206dffa5eca8a4dd6b to your computer and use it in GitHub Desktop.
/// <summary>
/// Italian fiscal id for companies
/// </summary>
public class PartitaIva: SimpleValueObject<string>
{
public const int MaxLength = 255;
public PartitaIva(string value) : base(value) { }
private static readonly int[] _oddMap = new int[] { 0, 2, 4, 6, 8, 1, 3, 5, 7, 9 };
private static bool CheckSum(string value)
{
// https://github.com/MrBogomips/ScalaExtractorsLib/blob/master/lib/src/main/scala/com/computableideas/lib/extractors/biz/it/PartitaIva.scala
Debug.Assert(value.Length == 11);
int c0 = '0';
int acc = 0;
for (var pos = 0; pos < 11; ++pos)
{
int ci = value[pos] - c0;
if (pos % 2 == 0) acc += ci;
else acc += _oddMap[ci];
}
return acc % 10 == 0;
}
public static Result<PartitaIva> From(string value)
{
if (Guard.String.IsNullOrEmpty(nameof(value), value, out var message)) // TODO: use guard
return Result.Failure<PartitaIva>(message);
if (Guard.String.IsNullOrTooLong(nameof(value), value, MaxLength, out message))
return Result.Failure<PartitaIva>(message);
if (!value.All(c => char.IsDigit(c)))
return Result.Failure<PartitaIva>(ErrorMessages.PartitaIva.InvalidFormat(value));
if (!CheckSum())
return Result.Failure<PartitaIva>(ErrorMessages.PartitaIva.InvalidCheckSum(value));
return new PartitaIva(value);
bool CheckSum()
{
int c0 = '0';
int acc = 0;
for (var pos = 0; pos < 11; ++pos)
{
int ci = value[pos] - c0;
if (pos % 2 == 0) acc += ci;
else acc += _oddMap[ci];
}
return acc % 10 == 0;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment