This repository has been archived by the owner on Nov 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 280
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor: rewrites "sortTransactions" to TypeScript
- Loading branch information
1 parent
263cf85
commit 478d7d7
Showing
2 changed files
with
61 additions
and
42 deletions.
There are no files selected for viewing
This file was deleted.
Oops, something went wrong.
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,61 @@ | ||
import { RESTMethod, Transaction } from './general'; | ||
|
||
const sortedMethods: RESTMethod[] = [ | ||
RESTMethod.CONNECT, | ||
RESTMethod.OPTIONS, | ||
RESTMethod.POST, | ||
RESTMethod.GET, | ||
RESTMethod.HEAD, | ||
RESTMethod.PUT, | ||
RESTMethod.PATCH, | ||
RESTMethod.DELETE, | ||
RESTMethod.TRACE, | ||
]; | ||
|
||
// Often, API description is arranged with a sequence of methods that lends | ||
// itself to understanding by the human reading the documentation. | ||
// | ||
// However, the sequence of methods may not be appropriate for the machine | ||
// reading the documentation in order to test the API. | ||
// | ||
// By sorting the transactions by their methods, it is possible to ensure that | ||
// objects are created before they are read, updated, or deleted. | ||
export default function sortTransactions( | ||
transactions: Transaction[], | ||
): Transaction[] { | ||
// Convert the list of transactions into a list of tuples | ||
// that hold each trasnaction index and details. | ||
const tempTransactions: Array<[number, Transaction]> = transactions.map( | ||
(transaction, index) => [index, transaction], | ||
); | ||
|
||
tempTransactions.sort( | ||
([leftIndex, leftTransaction], [rightIndex, rightTransaction]) => { | ||
const methodIndexA = sortedMethods.indexOf( | ||
leftTransaction.request.method, | ||
); | ||
const methodIndexB = sortedMethods.indexOf( | ||
rightTransaction.request.method, | ||
); | ||
|
||
// Sort transactions according to the transaction's request method | ||
if (methodIndexA < methodIndexB) { | ||
return -1; | ||
} | ||
|
||
if (methodIndexA > methodIndexB) { | ||
return 1; | ||
} | ||
|
||
// In case two transactions' request methods are the same, | ||
// preserve the original order of those transactions | ||
return leftIndex - rightIndex; | ||
}, | ||
); | ||
|
||
const cleanTransactions = tempTransactions.map( | ||
([_, transaction]) => transaction, | ||
); | ||
|
||
return cleanTransactions; | ||
} |