-
-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
50 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
import { describe, expect, test } from "@jest/globals"; | ||
import { normaliseSequenceDiff } from "./normaliseSequenceDiff"; | ||
|
||
describe("normaliseSequenceDiff", () => { | ||
test("simple", async () => { | ||
expect(normaliseSequenceDiff([])).toStrictEqual([]); | ||
expect(normaliseSequenceDiff([1])).toStrictEqual([0]); | ||
expect(normaliseSequenceDiff([2])).toStrictEqual([0]); | ||
expect(normaliseSequenceDiff([2], { startFrom: -1 })).toStrictEqual([-3]); | ||
expect(normaliseSequenceDiff([1, 2, 3])).toStrictEqual([0, 0, 0]); | ||
expect(normaliseSequenceDiff([1, 2, 4])).toStrictEqual([0, 0, -1]); | ||
expect(normaliseSequenceDiff([2, 4, 6])).toStrictEqual([0, -1, -2]); | ||
expect(normaliseSequenceDiff([2, 2, 6])).toStrictEqual([0, 1, -2]); | ||
expect(normaliseSequenceDiff([-1, 2, 6], { startFrom: 0 })).toStrictEqual([ | ||
1, -1, -4, | ||
]); | ||
// untidy sequence | ||
expect( | ||
normaliseSequenceDiff([-1, -10, 6, 4], { startFrom: 0 }) | ||
).toStrictEqual([2, 10, -3, -2]); | ||
expect(normaliseSequenceDiff([-1, -10, 6, 4])).toStrictEqual([ | ||
-8, 0, -13, -12, | ||
]); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
import { min } from "./min"; | ||
|
||
export const normaliseSequenceDiff = ( | ||
sequence: number[], | ||
options: { startFrom?: number } = {} | ||
): number[] => { | ||
const base = options?.startFrom ?? min(sequence); | ||
|
||
const sortedIndexes = getIndexesOfSortedArray(sequence); | ||
|
||
return sortedIndexes.reduce((diffArray, sortedIndex, index) => { | ||
diffArray[sortedIndex] = base + index - sequence[sortedIndex]; | ||
return diffArray; | ||
}, [] as number[]); | ||
}; | ||
|
||
const getIndexesOfSortedArray = (arr: number[]): number[] => { | ||
// Create an array of indexes | ||
const indexes = arr.map((_, index) => index); | ||
|
||
// Sort the indexes based on the corresponding values in the original array | ||
indexes.sort((a, b) => (arr[a] < arr[b] ? -1 : arr[a] > arr[b] ? 1 : 0)); | ||
|
||
return indexes; | ||
}; |