Skip to content

Commit

Permalink
Move appendArray
Browse files Browse the repository at this point in the history
  • Loading branch information
ehmicky committed Nov 14, 2021
1 parent 94e2e64 commit 7703abb
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 11 deletions.
10 changes: 10 additions & 0 deletions src/stats/append.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// Append two arrays in a performant way
export const appendArray = function (bigArray, smallArray) {
const smallArrayLength = smallArray.length

// eslint-disable-next-line fp/no-loops, fp/no-let, fp/no-mutation
for (let index = 0; index !== smallArrayLength; index += 1) {
// eslint-disable-next-line fp/no-mutating-methods
bigArray.push(smallArray[index])
}
}
14 changes: 3 additions & 11 deletions src/stats/merge.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { appendArray } from './append.js'

// Merges two sorted arrays.
// For better performance, the bigger array should be first.
// The first array is directly mutated. The second is not mutated.
// This is faster than just doing `Array.concat()` then `Array.sort()` and has
// a `O(n)` time complexity.
// For performance, if `bigArray` is empty, we just copy `smallArray` over.
export const mergeSort = function (bigArray, smallArray) {
if (bigArray.length === 0) {
appendArray(bigArray, smallArray)
Expand All @@ -17,17 +20,6 @@ export const mergeSort = function (bigArray, smallArray) {
mergeValues(bigArray, smallArray)
}

// For performance, if `bigArray` is empty, we just copy `smallArray` over.
const appendArray = function (bigArray, smallArray) {
const smallArrayLength = smallArray.length

// eslint-disable-next-line fp/no-loops, fp/no-let, fp/no-mutation
for (let index = 0; index !== smallArrayLength; index += 1) {
// eslint-disable-next-line fp/no-mutating-methods
bigArray.push(smallArray[index])
}
}

// Resize `bigArray` so it can receive the new elements from `smallArray`.
// Resizing an array is slow, so we do this in the most performant way.
// Any element could be copied. We're only looking to extend the size of
Expand Down

0 comments on commit 7703abb

Please sign in to comment.