diff --git a/source/Ox/js/Format.js b/source/Ox/js/Format.js index 77a66378..1b5a5cc9 100644 --- a/source/Ox/js/Format.js +++ b/source/Ox/js/Format.js @@ -639,6 +639,43 @@ Ox.formatDuration = function(seconds/*, decimals, format*/) { })).join(format == 'none' ? ':' : ' '); }; +/* +Ox.formatISBN Formats a string as an ISBN of a given length (10 or 13) + (isbn, length) -> ISBN + isbn ISBN + length length (10 or 13) + > Ox.formatISBN('0-306-40615-2', 13) + '9780306406157' + > Ox.formatISBN('978-0-306-40615-7', 10) + '0306406152' +*/ +Ox.formatISBN = function(isbn, length) { + var ret = ''; + function getCheckDigit(isbn) { + var mod = isbn.length == 10 ? 11 : 10 + return (mod - Ox.sum( + isbn.slice(0, -1).split('').map(function(digit, index) { + return isbn.length == 10 + ? parseInt(digit) * (10 - index) + : parseInt(digit) * (index % 2 == 0 ? 1 : 3); + }) + ) % mod + '').replace('10', 'X'); + } + isbn = isbn.toUpperCase().replace(/[^\dX]/g, ''); + if (( + (isbn.length == 10 && isbn.slice(0, -1).indexOf('X') == -1) + || (isbn.length == 13 && isbn.slice(0, 3) == '978') + ) && isbn.slice(-1) == getCheckDigit(isbn)) { + if (isbn.length == length) { + ret = isbn + } else { + isbn = isbn.length == 10 ? '978' + isbn : isbn.slice(3); + ret = isbn.slice(0, -1) + getCheckDigit(isbn); + } + } + return ret; +}; + /*@ Ox.formatNumber Formats a number with thousands separators (num, dec) -> format number to string