add Ox.formatISBN

This commit is contained in:
rlx 2016-01-11 14:51:31 +05:30
parent bb8ac55513
commit df32ec9ebc

View file

@ -639,6 +639,43 @@ Ox.formatDuration = function(seconds/*, decimals, format*/) {
})).join(format == 'none' ? ':' : ' '); })).join(format == 'none' ? ':' : ' ');
}; };
/*
Ox.formatISBN <f> Formats a string as an ISBN of a given length (10 or 13)
(isbn, length) -> <s> ISBN
isbn <s> ISBN
length <n> 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 <f> Formats a number with thousands separators Ox.formatNumber <f> Formats a number with thousands separators
(num, dec) -> <s> format number to string (num, dec) -> <s> format number to string