Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- module BrazilianUtils.Helpers
- open System
- let isNotRepdigit (value: int list) =
- value
- |> Seq.forall (fun elem -> elem = value.[0])
- |> not
- let charToInt (c : char) = int c - int '0'
- let onlyNumbers value =
- value
- |> String.filter Char.IsDigit
- let stringToIntList value =
- value
- |> onlyNumbers
- |> Seq.map charToInt
- |> Seq.toList
- let hasValue value =
- Seq.length value <> 0
- let calculateModulus11 weights (value: int list) =
- weights
- |> List.mapi (fun i weight -> value.[i] * weight)
- |> List.sum
- |> (fun x -> x % 11)
- let generateRandomNumbers count =
- let rnd = System.Random()
- List.init count (fun _ -> rnd.Next(0, 9))
- let hasLength length value =
- List.length value = length
- module BrazilianUtils.Cpf
- open Helpers
- open System.Text
- let private cpfLength = 11
- let private firstCheckDigitWeights = [ 10..-1..2 ]
- let private secondCheckDigitWeights = [ 11..-1..2 ]
- let private digitRule digit =
- match digit with
- | 0 | 1 -> 0
- | _ -> 11 - digit
- let private calculateDigit weights value =
- value
- |> calculateModulus11 weights
- |> digitRule
- let private validateCheckDigit value weights checkDigit =
- value
- |> calculateDigit weights
- |> ((=) checkDigit)
- let private isValidFirstCheckDigit (value : int list) =
- let checkDigitPos = 9
- let checkDigit = value.[checkDigitPos]
- validateCheckDigit value firstCheckDigitWeights checkDigit
- let private isValidSecondCheckDigit (value : int list) =
- let checkDigitPos = 10
- let checkDigit = value.[checkDigitPos]
- validateCheckDigit value secondCheckDigitWeights checkDigit
- let private hasCpfLength = hasLength cpfLength
- // Visible members
- let IsValid cpf =
- let cpf' = stringToIntList cpf
- [ hasValue; hasCpfLength; isNotRepdigit; isValidFirstCheckDigit; isValidSecondCheckDigit ]
- |> Seq.forall (fun validator -> validator cpf')
- let Format cpf =
- let clearValue = onlyNumbers cpf
- StringBuilder(clearValue).Insert(3, ".").Insert(7, ".").Insert(11, "-").ToString()
- let Generate () =
- let baseCpf = generateRandomNumbers (cpfLength - 2)
- let firstCheckDigit = calculateDigit firstCheckDigitWeights baseCpf
- let secondCheckDigit = calculateDigit secondCheckDigitWeights (baseCpf@[firstCheckDigit])
- baseCpf @ [firstCheckDigit] @ [secondCheckDigit]
- |> List.map (fun x -> x.ToString())
- |> String.concat ""
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement