文字列の型判定と安全比較ユーティリティ
string-utils.js
/**
* string-utils.js
*
* 安全な文字列比較・型判定を提供する軽量ユーティリティライブラリ
*
* 主な関数:
* - getStringType(value): 文字列の型を判定("primitive" | "object" | その他)
* - safeStringEqual(a, b, options): 型を吸収して安全に文字列比較
*/
/**
* 文字列の型を判定
* @param {*} value - 判定対象
* @returns {string} "primitive" | "object" | その他の型名
*/
export function getStringType(value) {
if (typeof value === "string") return "primitive";
if (value instanceof String) return "object";
return typeof value;
}
/**
* 文字列を安全に比較する関数
* プリミティブ文字列と String オブジェクトの違いを吸収
*
* @param {*} a - 比較対象1
* @param {*} b - 比較対象2
* @param {Object} [options] - 比較オプション
* @param {boolean} [options.ignoreCase=false] - 大文字小文字を無視する
* @param {boolean} [options.trim=false] - 前後の空白を無視する
* @returns {boolean} 比較結果
*/
export function safeStringEqual(a, b, options = {}) {
const { ignoreCase = false, trim = false } = options;
// null / undefined の安全な扱い
if (a == null && b == null) return true;
if (a == null || b == null) return false;
// String オブジェクト → プリミティブへ変換
if (a instanceof String) a = a.valueOf();
if (b instanceof String) b = b.valueOf();
// 型チェック
if (typeof a !== "string" || typeof b !== "string") return false;
// オプション処理
if (trim) {
a = a.trim();
b = b.trim();
}
if (ignoreCase) {
a = a.toLowerCase();
b = b.toLowerCase();
}
return a === b;
}
/**
* 文字列を安全に正規化(オプション処理だけ適用)
* 比較前に前処理したい場合に便利
*
* @param {*} value - 対象の値
* @param {Object} [options] - オプション(ignoreCase / trim)
* @returns {string|null} 正規化された文字列 or null(非文字列)
*/
export function normalizeString(value, options = {}) {
const { ignoreCase = false, trim = false } = options;
if (value == null) return null;
if (value instanceof String) value = value.valueOf();
if (typeof value !== "string") return null;
if (trim) value = value.trim();
if (ignoreCase) value = value.toLowerCase();
return value;
}
JavaScript使用例
import { safeStringEqual, getStringType, normalizeString } from './string-utils.js';
// --- 型判定 ---
console.log(getStringType("abc")); // "primitive"
console.log(getStringType(new String("abc"))); // "object"
console.log(getStringType(123)); // "number"
// --- 安全比較 ---
console.log(safeStringEqual("Hello", new String("hello"), { ignoreCase: true })); // ✅ true
console.log(safeStringEqual(" JS ", "js", { trim: true, ignoreCase: true })); // ✅ true
console.log(safeStringEqual("abc", "xyz")); // ❌ false
console.log(safeStringEqual("abc", 123)); // ❌ false
// --- 正規化してから別処理 ---
const normalized = normalizeString(" Hello ", { trim: true, ignoreCase: true });
console.log(normalized); // "hello"
JavaScript特徴まとめ
| 機能 | 説明 |
|---|---|
| ✅ プリミティブ/オブジェクト両対応 | "abc" も new String("abc") も安全に扱う |
| ⚙️ オプション | ignoreCase, trim で柔軟な比較 |
| 🛡️ 型安全 | 数値・配列などを自動的に弾く |
| 🔍 テストしやすい | normalizeString() で個別処理も可能 |
拡張アイデア
- 🔠 全角/半角の正規化機能(例:ひらがな⇔カタカナ)
- 🈁 Unicode 正規化(NFC/NFD対応)
- 🧪 文字列比較レポート機能(どこが違うか diff で出力)
- 🧩 TypeScript 型定義付き版

