diff --git a/include/faker-cxx/Commerce.h b/include/faker-cxx/Commerce.h index 765ea6754..fdc149af7 100644 --- a/include/faker-cxx/Commerce.h +++ b/include/faker-cxx/Commerce.h @@ -85,5 +85,49 @@ class Commerce * @endcode */ static std::string productFullName(); + + /** + * @brief Returns a random valid ean13 code. + * + * @returns Ean13 code. + * + * @code + * Commerce::EAN13() // "1234567890128" + * @endcode + */ + static std::string EAN13(); + + /** + * @brief Returns a random valid ean8 code. + * + * @returns Ean8 code. + * + * @code + * Commerce::EAN8() // "90311017" + * @endcode + */ + static std::string EAN8(); + + /** + * @brief Returns a random valid isbn13 code. + * + * @returns Isbn13 code. + * + * @code + * Commerce::ISBN13() // "9781234567897" + * @endcode + */ + static std::string ISBN13(); + + /** + * @brief Returns a random valid ISBN10 code. + * + * @returns Isbn10 code. + * + * @code + * Commerce::ISBN10() // "0200716018" + * @endcode + */ + static std::string ISBN10(); }; } diff --git a/src/modules/commerce/Commerce.cpp b/src/modules/commerce/Commerce.cpp index d1655ae9e..340881e8c 100644 --- a/src/modules/commerce/Commerce.cpp +++ b/src/modules/commerce/Commerce.cpp @@ -45,15 +45,62 @@ std::string Commerce::productFullName() std::string EAN13() { - std::string barcode = String::numeric(12, false); + std::string ean13 = String::numeric(12, false); int sum = 0; for (size_t i = 0; i < 12; i++) { - sum += (i % 2 == 0) ? (barcode[i] - '0') : 3 * (barcode[i] - '0'); + sum += (i % 2 == 0) ? (ean13[i] - '0') : 3 * (ean13[i] - '0'); } - int checkDigit = (10 - (sum % 10)) % 10; + + int checkDigit = 10 - (sum % 10); - return barcode + std::to_string(checkDigit); + return ean13 + std::to_string(checkDigit); +} + +std::string EAN8() +{ + std::string ean8 = String::numeric(7, false); + + int sum = 0; + for (size_t i = 0; i < 7; i++) + { + sum += (i % 2 == 0) ? (ean8[i] - '0') : 3 * (ean8[i] - '0'); + } + + int checkDigit = 10 - (sum % 10); + + return ean8 + std::to_string(checkDigit); +} + +std::string ISBN13() +{ + std::string isbn13 = String::numeric(12, true); + + int sum = 0; + for (size_t i = 0; i < 12; i++) + { + sum += (i % 2 == 0) ? (isbn13[i] - '0') : 3 * (isbn13[i] - '0'); + } + + int checkDigit = 10 - (sum % 10); + + return isbn13 + std::to_string(checkDigit); +} + +std::string ISBN10() +{ + std::string isbn10 = String::numeric(9, true); + + int sum = 0, weight = 10; + for (size_t i = 0; i < 9; i++) + { + sum += isbn10[i] * weight; + weight--; + } + + int checkDigit = 10 - (sum % 10); + + return isbn10 + std::to_string(checkDigit); } }