Last active
August 12, 2020 18:24
-
-
Save micheltlutz/02a2b97bf441f99ad94e7e978161a5e3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
extension Collection where Element == Int { | |
var digitCNPJ: Int { | |
let upperBound = 9 | |
let lowerBound = 2 | |
let mod = 11 | |
let secondMod = 10 | |
let factors = Array((lowerBound...upperBound).reversed()) | |
let multiplied = self.reversed().enumerated().map { | |
return $0.element * factors[$0.offset % factors.count] | |
} | |
let sum = multiplied.reduce(0, +) | |
return (sum % mod) % secondMod | |
} | |
} | |
extension StringProtocol { | |
var isValidCNPJ: Bool { | |
let numbers = compactMap(\.wholeNumberValue) | |
guard numbers.count == 14 && Set(numbers).count != 1 else { return false } | |
let digits = Array(numbers[0..<12]) | |
let firstDigit = checkDigitCNPJ(for: digits, upperBound: 9, lowerBound: 2, mod: 11) | |
let secondDigit = checkDigitCNPJ(for: digits + [firstDigit], upperBound: 9, lowerBound: 2, mod: 11) | |
return firstDigit == numbers[12] && secondDigit == numbers[13] | |
} | |
var isValidCNPJ: Bool { | |
let numbers = compactMap(\.wholeNumberValue) | |
guard numbers.count == 14 && Set(numbers).count != 1 else { return false } | |
return numbers.prefix(12).digitCNPJ == numbers[12] && | |
numbers.prefix(13).digitCNPJ == numbers[13] | |
} | |
} | |
// Usage | |
let cnpj = "29.957.575/0001-89".isValidCNPJ // true | |
//let cnpj = "16.914.610/0001-30".isValidCNPJ // true | |
//let cnpj = "16914610000130".isValidCNPJ // true | |
//let cnpj = "66666666666666".isValidCNPJ // false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment