0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Intl.Collatorの比較結果をSKUの同一性判定に使わない

0
Posted at

表示上の並び順と、在庫キーの同一性は別の判断です。海外向け一件発送と倉庫履約の一覧を作る例で、数値を意識した並び替えを有効にしても、異なるSKUを同じキーとしてまとめないようにします。

Intl.Collator のオプションには numeric や sensitivity があります。以下の設定では、文字列が異なる A2 と a02 の比較結果がゼロになります。ゼロはこの比較条件での同等性であり、商品が同一という業務上の承認ではありません。

表示用の比較に明示的な同順位処理を足す

const assert = require('node:assert/strict');
const collator = new Intl.Collator('en', {
  numeric: true,
  sensitivity: 'base'
});

function compareDisplaySku(a, b) {
  if (typeof a !== 'string' || typeof b !== 'string') {
    throw new TypeError('string SKU required');
  }
  const display = collator.compare(a, b);
  if (display !== 0) return display;
  return a === b ? 0 : (a < b ? -1 : 1);
}

assert.equal(collator.compare('A2', 'a02'), 0);
const skus = ['A10', 'a02', 'A2'];
const before = skus.slice();
const sorted = skus.slice().sort(compareDisplaySku);
assert.deepEqual(sorted, ['A2', 'a02', 'A10']);
assert.deepEqual(skus, before);
assert.equal(new Map(skus.map(sku => [sku, 1])).size, 3);
assert.notEqual(compareDisplaySku('A2', 'a02'), 0);
assert.equal(compareDisplaySku('A2', 'A2'), 0);
assert.equal(
  Math.sign(compareDisplaySku('A2', 'a02')),
  -Math.sign(compareDisplaySku('a02', 'A2'))
);
assert.throws(() => compareDisplaySku('A2', null), /string SKU/);
console.log('display sorting keeps distinct keys');

Node.js 24でこの最終コードを実行し、表示順、入力配列の維持、異なるキーの保持を確認しました。元のSKUは変換せず、同順位の表示だけを文字列の比較で決めています。

この順序を永続的なID生成やデータベースの一意性制約へ流用するものではありません。ロケールや設定を変える場合は表示結果を確認し、商品を統合する必要があるときは別の承認済みマッピングを使用してください。実店舗との接続や実在庫の検証を行った例ではありません。

倉庫内でパレットに載せて保管されている段ボール箱。

倉庫内でパレットに載せて保管されている段ボール箱。

AI支援で作成し、最終コードをNode.js 24で実行確認した技術ノートです。

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?