เราต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงสองตัวและตัวเลข n ฟังก์ชันจะจับคู่สตริงทั้งสอง คือตรวจสอบว่าสตริงทั้งสองมีตัวอักษรเหมือนกัน ฟังก์ชันควรคืนค่า true หากทั้งสองมีตัวอักษรเหมือนกันไม่ว่าลำดับ หรือมีตัวอักษรต่างกันสูงสุด n ตัว มิฉะนั้นคืนค่า false
มาเขียนโค้ดสำหรับฟังก์ชันนี้กัน
ตัวอย่าง
const str1 = 'first string';
const str2 = 'second string';
const wildcardMatching = (first, second, num) => {
let count = 0;
for(let i = 0; i < first.length; i++){
if(!second.includes(first[i])){
count++;
};
if(count > num){
return false;
};
};
return true;
};
console.log(wildcardMatching(str1, str2, 2));
console.log(wildcardMatching(str1, str2, 1));
console.log(wildcardMatching(str1, str2, 0));
ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็นดังนี้
true true false