Skip to content
This repository has been archived by the owner on Nov 8, 2024. It is now read-only.

Commit

Permalink
refactor: rewrites "sortTransactions" to TypeScript
Browse files Browse the repository at this point in the history
  • Loading branch information
artem-zakharchenko committed Oct 8, 2019
1 parent 263cf85 commit 478d7d7
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 42 deletions.
42 changes: 0 additions & 42 deletions packages/dredd/lib/sortTransactions.js

This file was deleted.

61 changes: 61 additions & 0 deletions packages/dredd/lib/sortTransactions.ts
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;
}

0 comments on commit 478d7d7

Please sign in to comment.