Skip to content

Commit

Permalink
move mergeTwoSortedArrays to separate file
Browse files Browse the repository at this point in the history
  • Loading branch information
geoffrey-wu committed Sep 11, 2024
1 parent f807b35 commit 1276a62
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 45 deletions.
46 changes: 1 addition & 45 deletions database/qbreader/get-frequency-list.js
Original file line number Diff line number Diff line change
@@ -1,50 +1,6 @@
import { bonuses, tossups } from './collections.js';

import { DIFFICULTIES } from '../../constants.js';

/**
* Merge two sorted arrays into a single sorted array.
* The two arrays should be sorted by the key function.
* @template T
* @param {T[]} array1
* @param {T[]} array2
* @param {(arg: T) => number} keyFunction - the function to extract the key from each element.
* @param {(arg1: T, arg2: T) => T} combineFunction - the function to combine two elements with the same key.
* @returns {T[]} The merged array.
*/
function mergeTwoSortedArrays (array1, array2, keyFunction, combineFunction) {
const mergedArray = [];
let i = 0;
let j = 0;

while (i < array1.length && j < array2.length) {
const key1 = keyFunction(array1[i]);
const key2 = keyFunction(array2[j]);
if (key1 < key2) {
mergedArray.push(array1[i]);
i++;
} else if (key1 > key2) {
mergedArray.push(array2[j]);
j++;
} else {
mergedArray.push(combineFunction(array1[i], array2[j]));
i++;
j++;
}
}

while (i < array1.length) {
mergedArray.push(array1[i]);
i++;
}

while (j < array2.length) {
mergedArray.push(array2[j]);
j++;
}

return mergedArray;
}
import mergeTwoSortedArrays from '../../merge-two-sorted-arrays.js';

/**
* Get a frequency list of answers for a given subcategory and difficulty.
Expand Down
43 changes: 43 additions & 0 deletions merge-two-sorted-arrays.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/**
* Merge two sorted arrays into a single sorted array.
* The two arrays should be sorted by the key function.
* @template T
* @param {T[]} array1
* @param {T[]} array2
* @param {(arg: T) => number} keyFunction - the function to extract the key from each element.
* @param {(arg1: T, arg2: T) => T} combineFunction - the function to combine two elements with the same key.
* @returns {T[]} The merged array.
*/
export default function mergeTwoSortedArrays (array1, array2, keyFunction, combineFunction) {
const mergedArray = [];
let i = 0;
let j = 0;

while (i < array1.length && j < array2.length) {
const key1 = keyFunction(array1[i]);
const key2 = keyFunction(array2[j]);
if (key1 < key2) {
mergedArray.push(array1[i]);
i++;
} else if (key1 > key2) {
mergedArray.push(array2[j]);
j++;
} else {
mergedArray.push(combineFunction(array1[i], array2[j]));
i++;
j++;
}
}

while (i < array1.length) {
mergedArray.push(array1[i]);
i++;
}

while (j < array2.length) {
mergedArray.push(array2[j]);
j++;
}

return mergedArray;
}

0 comments on commit 1276a62

Please sign in to comment.