/// Searches a 2D matrix using short-circuiting array methods (`some`).
function searchMatrixFunctional(matrix, target) {
let coordinates = null;
// .some() stops execution as soon as any row returns true
matrix.some((row, i) => {
return row.some((value, j) => {
if (value === target) {
coordinates = { row: i, col: j };
return true; // Signals row.some to stop
}
return false;
});
});
return coordinates;
}
function mainAlternative() {
const matrix = [
[5, 12, 19],
[22, 35, 41],
[50, 68, 74]
];
const target = 35;
const result = searchMatrixFunctional(matrix, target);
if (result) {
console.log(`[Functional Approach] Found target at row ${result.row}, col ${result.col}`);
} else {
console.log("[Functional Approach] Target not found.");
}
}
mainAlternative();
/*
run:
[Functional Approach] Found target at row 1, col 1
*/