LoginSignup
20
19

More than 5 years have passed since last update.

JavaScriptで10桁のISBNを13桁に変換する

Last updated at Posted at 2019-02-01

ISBN は、International Standard Book Numberの略で、
世界共通で使える、書籍を特定する為の番号。

昔は10桁だったが、番号が枯渇しそうになったらしく、今は13桁に拡張されている。
下位互換のため、過去に発番された10桁の番号を13桁に変換する方法が策定されている。

10桁を13桁に変換する方法

477414813X を例に。

  1. 先頭に978を足して、末尾の1桁を除く
    • 978477414813
    • ※フランス、韓国、イタリアの場合、979を使ったりもする
  2. 先頭の桁から順に1、3、1、3…を掛けて合計する
    • 9*1 + 7*3 + 8*1 + 4*3 + 7*1 + 7*3 + 4*1 + 1*3 + 4*1 + 8*3 + 1*1 + 3*3 = 123
  3. 合計を10で割った余りを10から引く
    • 10 - (123 % 10) = 7
    • ※引き算の結果が10の時は0とする
  4. 1.の末尾に3.の値を添えて出来上がり
    • 9784774148137

10桁を13桁に変換するコード

const toISBN13 = (isbn10) => {
  // 1. 先頭に`978`を足して、末尾の1桁を除く
  const src = `978${isbn10.slice(0, 9)}`;

  // 2. 先頭の桁から順に1、3、1、3…を掛けて合計する
  const sum = src.split('').map(s => parseInt(s))
      .reduce((p, c, i) => p + ((i % 2 === 0) ? c : c * 3));

  // 3. 合計を10で割った余りを10から引く(※引き算の結果が10の時は0とする)
  const rem = 10 - sum % 10;
  const checkdigit = rem === 10 ? 0 : rem;

  // 1.の末尾に3.の値を添えて出来上がり
  return `${src}${checkdigit}`;
};
20
19
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
19