Are you an LLM? Read llms.txt for a summary of the docs, or llms-full.txt for the full context.
sortedInsert – Uniswap SDK
Skip to content

sortedInsert

Inserts an item into a sorted array while maintaining sort order and size constraints.

Import

import { sortedInsert } from '@uniswap/sdk-core-next'

Function Signature

function sortedInsert<T>(
  items: T[],
  add: T,
  maxSize: number,
  comparator: (a: T, b: T) => number
): T | null

Parameters

NameTypeDescription
itemsT[]The sorted array to insert into (modified in place)
addTThe item to insert
maxSizenumberMaximum array size
comparator(a: T, b: T) => numberComparison function (negative if a < b)

Returns

T | null - The removed item if the array was at max capacity, otherwise null.

Example

import { sortedInsert } from '@uniswap/sdk-core-next'
 
// Numeric comparator (ascending)
const compareNumbers = (a: number, b: number) => a - b
 
// Start with empty array
const items: number[] = []
 
// Insert items, max size 3
sortedInsert(items, 5, 3, compareNumbers)  // returns null, items = [5]
sortedInsert(items, 3, 3, compareNumbers)  // returns null, items = [3, 5]
sortedInsert(items, 7, 3, compareNumbers)  // returns null, items = [3, 5, 7]
sortedInsert(items, 4, 3, compareNumbers)  // returns 7, items = [3, 4, 5]
sortedInsert(items, 1, 3, compareNumbers)  // returns 5, items = [1, 3, 4]
sortedInsert(items, 10, 3, compareNumbers) // returns 10, items = [1, 3, 4] (10 not inserted)

Use Cases

Best Trades

Finding the best N trades by output amount:

import { sortedInsert, CurrencyAmount, type Currency } from '@uniswap/sdk-core-next'
 
interface Trade {
  outputAmount: CurrencyAmount<Currency>
  // ... other fields
}
 
// Comparator: better trades first (higher output)
const compareTrades = (a: Trade, b: Trade): number => {
  if (a.outputAmount.greaterThan(b.outputAmount)) return -1
  if (a.outputAmount.lessThan(b.outputAmount)) return 1
  return 0
}
 
const bestTrades: Trade[] = []
const MAX_RESULTS = 3
 
for (const trade of allPossibleTrades) {
  sortedInsert(bestTrades, trade, MAX_RESULTS, compareTrades)
}
 
// bestTrades now contains the top 3 trades by output amount

Price-Sorted Orders

interface Order {
  price: bigint
  amount: bigint
}
 
// Ascending price (best buy orders)
const compareByPrice = (a: Order, b: Order): number => {
  if (a.price < b.price) return -1
  if (a.price > b.price) return 1
  return 0
}
 
const orderBook: Order[] = []
 
// Add orders, keeping only top 10
for (const order of incomingOrders) {
  sortedInsert(orderBook, order, 10, compareByPrice)
}

Complexity

  • Time: O(log n) for binary search + O(n) for insertion = O(n)
  • Space: O(1) (modifies array in place)

Invariants

The function enforces:

  • maxSize must be greater than 0
  • items.length must be at most maxSize (throws if violated)
// These will throw:
sortedInsert([], 1, 0, compareNumbers)     // maxSize must be > 0
sortedInsert([1, 2, 3, 4], 5, 3, compareNumbers) // array exceeds maxSize