UNPKG

lgrthms

Version:

Algorithms and data structures for your JavaScript and TypeScript projects 🧑‍💻

44 lines (43 loc) 1.53 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.searchInSortedMatrixIndexes = exports.searchInSortedMatrix = exports.searchInMatrixIndexes = exports.searchInMatrix = void 0; function searchInMatrix(matrix, target, get) { const [i, j] = searchInMatrixIndexes(matrix, target, get); return i !== -1 && j !== -1 ? matrix[i][j] : undefined; } exports.searchInMatrix = searchInMatrix; function searchInMatrixIndexes(matrix, target, get) { get = get ? get : (element) => element; for (let i = 0; i < matrix.length; i++) { for (let j = 0; j < matrix[i].length; j++) { if (target === get(matrix[i][j])) { return [i, j]; } } } return [-1, -1]; } exports.searchInMatrixIndexes = searchInMatrixIndexes; function searchInSortedMatrix(matrix, target, get) { const [i, j] = searchInSortedMatrixIndexes(matrix, target, get); return i !== -1 && j !== -1 ? matrix[i][j] : undefined; } exports.searchInSortedMatrix = searchInSortedMatrix; function searchInSortedMatrixIndexes(matrix, target, get) { get = get ? get : (element) => element; let i = 0; let j = matrix[i].length - 1; while (i < matrix.length && j >= 0) { if (target === get(matrix[i][j])) { return [i, j]; } if (target < get(matrix[i][j])) { j--; } else { i++; } } return [-1, -1]; } exports.searchInSortedMatrixIndexes = searchInSortedMatrixIndexes;