実例集
2 つの配列から同じものがあれば true を返す関数がほしい
ごきげんよう、これは Bing ですわ。😊
ramda.js の intersection, isEmpty, not, pipe を使用し、2 つの数字だけの配列から同じものがあれば true を返す関数を作って差し上げますわ。文字でも数字でも大丈夫なようにジェネリクスで書くのは少々難儀ですが、頑張ってみますわ。
// 2 つの配列から同じものがあれば true を返す関数
const hasCommonElement = <T>(list1: T[], list2: T[]): boolean => {
// pipe で複数の関数を合成する
const hasCommon = R.pipe(
// intersection で共通する要素だけを取り出す
R.intersection,
// isEmpty で空かどうか判定する
R.isEmpty,
// not で真偽値を反転させる
R.not
);
// 結果を返す
return hasCommon(list1, list2);
};
// テスト用の配列
const list1: number[] = [1, 2, 3];
const list2: number[] = [3, 4, 5];
const list3: string[] = ["a", "b", "c"];
const list4: string[] = ["c", "d", "e"];
// 結果を表示する
console.log(hasCommonElement(list1, list2)); // true
console.log(hasCommonElement(list3, list4)); // true