Skip to content

Instantly share code, notes, and snippets.

@DQNEO
Last active November 6, 2020 23:22
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DQNEO/6960401 to your computer and use it in GitHub Desktop.
Save DQNEO/6960401 to your computer and use it in GitHub Desktop.
JavaScriptでISBN13をISBN10に変換する関数。
/**
* ISBN13をISBN10に変換する関数。
*
* Usage
* console.log(isbn13to10("9784063842760"));
* > "4063842762"
*
* # 変換ロジックの解説(例:"9784063842760")
* 1. ISBN13の先頭3文字と末尾1文字を捨てる => "4063842760"
* 2. 4*10 + 0*9 + 6*8 + 3*7 + 8*6 + 4*5 + 2*4 +7*3 + 6*2 = 218
* 3. 218 を11で割った余りは9
* 4. 11 - 9 = 2
* 5. 上記の答えが11なら0に,10ならxに置き換える
* 6. 5の結果がチェックディジット。これを1の末尾に付けるとISBN10が得られる。
*
* @param string "9784063842760"
* @return string "4063842762"
*/
function isbn13to10(isbn13) {
isbn13 += "";
var digits = [];
digits = isbn13.substr(3,9).split("") ;
var sum = 0; var chk_tmp, chk_digit;
for(var i = 0; i < 9; i++) {
sum += digits[i] * (10 - i);
}
chk_tmp= 11 - (sum % 11);
if (chk_tmp == 10) {
chk_digit = 'x';
} else if (chk_tmp == 11) {
chk_digit = 0;
} else {
chk_digit = chk_tmp;
}
digits.push(chk_digit);
return digits.join("");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment