Вы почти на месте, и вы просто беспокоитесь о производительности, верно? Таким образом, для повышения производительности вашей программы вы можете использовать приятную технику, которая называется Memoization
Запоминание - это метод оптимизации, который используется главным образом для ускорения работы компьютерных программ путем сохранения результатов. дорогостоящих вызовов функций и возврата кэшированного результата, когда те же самые входы повторяются
const arr = [[22,23], [74,1], [21,33], [32,84], [11,31], [1,49], [7,8], [11,11], [99,68], [52,20]];
/**
* Here I create the momoized function which cache the
* column and if we want to get the same column then it
* simply return the previously cached column array
* otherwise, it get the column and cache it for future
* and return it.
*/
const memoized = () => {
const cache = {};
return (arr, index) => {
if (index in cache) {
return cache[index];
} else {
const col = arr.map(item => (item[index]));
cache[index] = col;
return col;
}
}
}
/**
* As memoized is a higher order function so it returns
* another function which will be executed by calling
* this getColumn function reference.
*/
const getColumn = memoized();
const getMinValue = (arr, col) => Math.min(...getColumn(arr, col));
const getMaxValue = (arr, col) => Math.max(...getColumn(arr, col));
const minValueIndex = (arr, col) => getColumn(arr, col).indexOf(getMinValue(arr, col));
const maxValueIndex = (arr, col) => getColumn(arr, col).indexOf(getMaxValue(arr, col));
console.log('minValue: ', getMinValue(arr, 0)); // Calculated
console.log('maxValue: ',getMaxValue(arr, 0)); // Cached
console.log('minValueIndex: ', minValueIndex(arr, 0)); // Cached
console.log('maxValueIndex: ', maxValueIndex(arr, 0)); // Cached
.as-console-wrapper {min-height: 100% !important; top: 0;}