Skip to content

Instantly share code, notes, and snippets.

@micheltlutz
Last active August 12, 2020 18:24
Show Gist options
  • Save micheltlutz/02a2b97bf441f99ad94e7e978161a5e3 to your computer and use it in GitHub Desktop.
Save micheltlutz/02a2b97bf441f99ad94e7e978161a5e3 to your computer and use it in GitHub Desktop.
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