PageSourceSearch

https://data-structure-typed-docs.vercel.app/assets/js/28221a83.ec65c8fa.js

js data-structure-typed-docs.vercel.app collected 2026-10-03 06:31:26 UTC 29,426 bytes, 1 lines download raw bytes

1"use strict";(globalThis.webpackChunkdocs_site_docusaurus=globalThis.webpackChunkdocs_site_docusaurus||[]).push([[928],{3565(e,n,t){t.r(n),t.d(n,{assets:()=>d,contentTitle:()=>a,default:()=>l,frontMatter:()=>i,metadata:()=>r,toc:()=>c});const r=JSON.parse('{"id":"guide/integrations","title":"Framework Integrations \u2014 React, Express, NestJS","description":"Integrate data-structure-typed with React, Express, NestJS, and other frameworks. Production-ready patterns.","source":"@site/docs/guide/integrations.md","sourceDirName":"guide","slug":"/guide/integrations","permalink":"/docs/guide/integrations","draft":false,"unlisted":false,"editUrl":"https://github.com/zrwusa/data-structure-typed/edit/main/docs-site-docusaurus/docs/guide/integrations.md","tags":[],"version":"current","frontMatter":{"sidebar_label":"INTEGRATIONS","description":"Integrate data-structure-typed with React, Express, NestJS, and other frameworks. Production-ready patterns.","title":"Framework Integrations \u2014 React, Express, NestJS","keywords":["data-structure-typed react","typescript data structures express","nestjs data structures","production patterns"]},"sidebar":"guideSidebar","previous":{"title":"GUIDES","permalink":"/docs/guide/guides"},"next":{"title":"ARCHITECTURE","permalink":"/docs/guide/architecture"}}');var s=t(4848),o=t(8453);const i={sidebar_label:"INTEGRATIONS",description:"Integrate data-structure-typed with React, Express, NestJS, and other frameworks. Production-ready patterns.",title:"Framework Integrations \u2014 React, Express, NestJS",keywords:["data-structure-typed react","typescript data structures express","nestjs data structures","production patterns"]},a="INTEGRATIONS",d={},c=[{value:"Table of Contents",id:"table-of-contents",level:2},{value:"React Integration",id:"react-integration",level:2},{value:"Use Case: Sorted State Management",id:"use-case-sorted-state-management",level:3},{value:"Express Integration",id:"express-integration",level:2},{value:"Use Case: LRU Cache Middleware",id:"use-case-lru-cache-middleware",level:3},{value:"Use Case: Rate Limiting with Deque",id:"use-case-rate-limiting-with-deque",level:3},{value:"Nest.js Integration",id:"nestjs-integration",level:2},{value:"Use Case: Product Price Index Service",id:"use-case-product-price-index-service",level:3},{value:"Use Case: Task Queue Controller",id:"use-case-task-queue-controller",level:3},{value:"TypeScript Configuration",id:"typescript-configuration",level:2},{value:"tsconfig.json for data-structure-typed",id:"tsconfigjson-for-data-structure-typed",level:3},{value:"Package.json Setup",id:"packagejson-setup",level:3},{value:"Import Patterns",id:"import-patterns",level:2},{value:"All Structures",id:"all-structures",level:3},{value:"Module Systems",id:"module-systems",level:3},{value:"Common Integration Patterns",id:"common-integration-patterns",level:2},{value:"Pattern 1: Dependency Injection (Nest.js)",id:"pattern-1-dependency-injection-nestjs",level:3},{value:"Pattern 2: React Hooks",id:"pattern-2-react-hooks",level:3},{value:"Troubleshooting",id:"troubleshooting",level:2},{value:"Issue: Import Error",id:"issue-import-error",level:3},{value:"Issue: Type Not Found",id:"issue-type-not-found",level:3},{value:"Issue: Performance in Development",id:"issue-performance-in-development",level:3}];function u(e){const n={a:"a",blockquote:"blockquote",code:"code",h1:"h1",h2:"h2",h3:"h3",header:"header",hr:"hr",li:"li",ol:"ol",p:"p",pre:"pre",strong:"strong",...(0,o.R)(),...e.components};return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(n.header,{children:(0,s.jsx)(n.h1,{id:"integrations",children:"INTEGRATIONS"})}),"\n",(0,s.jsx)(n.p,{children:"How to use data-structure-typed with React, Express, Nest.js, and other frameworks."}),"\n",(0,s.jsx)(n.p,{children:(0,s.jsxs)(n.strong,{children:[(0,s.jsx)(n.a,{href:"/docs/guide/quick-start",children:"Back to README"})," \u2022 ",(0,s.jsx)(n.a,{href:"/docs/guide/guides",children:"Code Examples"})," \u2022 ",(0,s.jsx)(n.a,{href:"/docs/guide/performance",children:"Performance"})]})}),"\n",(0,s.jsx)(n.hr,{}),"\n",(0,s.jsx)(n.h2,{id:"table-of-contents",children:"Table of Contents"}),"\n",(0,s.jsxs)(n.ol,{children:["\n",(0,s.jsx)(n.li,{children:(0,s.jsx)(n.a,{href:"#react-integration",children:"React Integration"})}),"\n",(0,s.jsx)(n.li,{children:(0,s.jsx)(n.a,{href:"#express-integration",children:"Express Integration"})}),"\n",(0,s.jsx)(n.li,{children:(0,s.jsx)(n.a,{href:"#nestjs-integration",children:"Nest.js Integration"})}),"\n",(0,s.jsx)(n.li,{children:(0,s.jsx)(n.a,{href:"#typescript-configuration",children:"TypeScript Configuration"})}),"\n"]}),"\n",(0,s.jsx)(n.hr,{}),"\n",(0,s.jsx)(n.h2,{id:"react-integration",children:"React Integration"}),"\n",(0,s.jsx)(n.h3,{id:"use-case-sorted-state-management",children:"Use Case: Sorted State Management"}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{className:"language-tsx",children:'import { useCallback, useMemo, useState } from \'react\';\nimport { RedBlackTree } from \'data-structure-typed\';\n\ninterface TodoItem {\n  id: number;\n  text: string;\n  completed: boolean;\n  priority: number;\n}\n\n/**\n * \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\n * \u2551 PERFORMANCE COMPARISON TABLE                                            \u2551\n * \u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563\n * \u2551 Operation       \u2551 RedBlackTree      \u2551 Array           \u2551 Speedup         \u2551\n * \u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563\n * \u2551 Add todo        \u2551 O(log n)          \u2551 O(n log n)      \u2551 Often much faster* \u2551\n * \u2551 Delete todo     \u2551 O(log n)          \u2551 O(n)            \u2551 Often faster*      \u2551\n * \u2551 Keep sorted     \u2551 Automatic \u2713       \u2551 Manual sort \u2717   \u2551 Less code          \u2551\n * \u2551 Rebalancing     \u2551 Self-balancing \u2713  \u2551 N/A             \u2551 N/A                \u2551\n * \u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563\n * \u2551 *See PERFORMANCE.md for measured benchmarks and how results scale.       \u2551\n * \u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d\n */\nexport default function TodoApp() {\n  const [text, setText] = useState(\'\');\n  const [priority, setPriority] = useState(5);\n\n  const [todos, setTodos] = useState(() =>\n    new RedBlackTree<TodoItem>([], {\n      // Comparator ensures todos are ALWAYS sorted by priority (descending)\n      // RedBlackTree maintains this order automatically on every insertion\n      // W
1ith Array, you\'d need to manually sort() after each add \u2192 expensive!\n      comparator: (a, b) => b.priority - a.priority\n    }));\n\n  const addTodo = useCallback(() => {\n    if (!text.trim()) return;\n\n    setTodos((prev) => {\n      const next = prev.clone();\n\n      // This insertion maintains sorted order automatically\n      // The Red-Black Tree algorithm handles all the balancing\n      next.add({\n        id: Date.now(),\n        text: text.trim(),\n        completed: false,\n        priority: Math.max(1, Math.min(10, priority)),\n      });\n      return next;\n    });\n\n  }, [text, priority]);\n\n  /**\n   * Delete a todo efficiently\n   *\n   * Performance Analysis:\n   * \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n   * \u2705 RedBlackTree.delete(): O(log n)\n   *    - For 1000 items: ~10 tree operations\n   *    - No need to shift array elements\n   *    - Red-Black Tree rebalances automatically\n   *\n   * \u274c Array Alternative:\n   *    - Array.findIndex(): O(n) to find the item\n   *    - Array.splice(): O(n) to remove and shift all elements\n   *    - For 1000 items: ~500 operations per delete\n   *    - Note: Actual wall-clock impact depends on your workload (rendering, GC, object shapes, etc.).\n   */\n  const deleteTodo = useCallback((todo: TodoItem) => {\n    setTodos((prev) => {\n      const next = prev.clone();\n      next.delete(todo); // \u2190 O(log n) deletion\n      return next;\n    });\n  }, []);\n\n  const todoList = useMemo(() => [...todos.keys()], [todos]);\n\n  return (\n    <div className="todo-app">\n      <h2>Priority Todos (Auto-Sorted)</h2>\n      <div className="input-section">\n        <input\n          type="text"\n          placeholder="Todo text"\n          value={text}\n          onChange={(e) => setText(e.target.value)}\n        />\n        <input\n          type="number"\n          min="1"\n          max="10"\n          placeholder="Priority (1-10)"\n          value={priority}\n          onChange={(e) =>\n            setPriority(Math.max(1, Math.min(10, Number(e.target.value))))\n          }\n        />\n        <button onClick={addTodo} disabled={!text.trim()}>\n          Add Todo\n        </button>\n      </div>\n      <ul className="todo-list">\n        {todoList.map((todo) => (\n          <li key={todo.id} className={todo.completed ? \'completed\' : \'\'}>\n            <input\n              type="checkbox"\n              checked={todo.completed}\n              onChange={() => {\n                setTodos((prev) => {\n                  const next = prev.clone();\n\n                  // Delete the old todo object\n                  next.delete(todo);\n                  next.add({ ...todo, completed: !todo.completed });\n                  return next;\n                });\n              }}\n            />\n            <span>{todo.text}</span>\n            <span className="priority">P{todo.priority}</span>\n            <button onClick={() => deleteTodo(todo)}>Delete</button>\n          </li>\n        ))}\n      </ul>\n    </div>\n  );\n}\n'})}),"\n",(0,s.jsx)(n.hr,{}),"\n",(0,s.jsx)(n.h2,{id:"express-integration",children:"Express Integration"}),"\n",(0,s.jsx)(n.h3,{id:"use-case-lru-cache-middleware",children:"Use Case: LRU Cache Middleware"}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{className:"language-javascript",children:"const  {DoublyLinkedList} = require('data-structure-typed');\n\nclass LRUCache {\n  constructor(capacity = 100) {\n    this.cache = new Map();\n    this.order = new DoublyLinkedList();\n    this.capacity = capacity;\n  }\n  get(key) {\n    if (!this.cache.has(key))\n      return null;\n    const { value, node } = this.cache.get(key);\n    // Move to end (most recently used)\n    this.order.delete(node);\n    const newNode = this.order.push(key);\n    this.cache.set(key, { value, node: newNode });\n    return value;\n  }\n  set(key, value) {\n    if (this.cache.has(key)) {\n      this.get(key); // Mark as recently used\n      this.cache.get(key).value = value;\n      return;\n    }\n    if (this.cache.size >= this.capacity) {\n      const lru = this.order.shift();\n      this.cache.delete(lru);\n    }\n    const node = this.order.push(key);\n    this.cache.set(key, { value, node });\n  }\n}\n\nmodule.exports = LRUCache;\n"})}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{className:"language-javascript",children:"// Usage in Express\nconst app = express();
1\nconst responseCache = new LRUCache(50);\napp.use((req, res, next) => {\n  const cachedResponse = responseCache.get(req.url);\n  if (cachedResponse) {\n    return res.status(cachedResponse.status).json(cachedResponse.data);\n  }\n  // Wrap original send to cache response\n  const originalSend = res.send;\n  res.send = function (data) {\n    responseCache.set(req.url, { status: res.statusCode, data });\n    return originalSend.call(this, data);\n  };\n  next();\n});\napp.get('/api/data', (req, res) => {\n  res.json({ message: 'Cached response' });\n});\napp.listen(3000);\n"})}),"\n",(0,s.jsx)(n.h3,{id:"use-case-rate-limiting-with-deque",children:"Use Case: Rate Limiting with Deque"}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{className:"language-typescript",children:"import { Deque } from 'data-structure-typed';\n\nclass RateLimiter {\n  private requests = new Map<string, Deque<number>>();\n  private limit: number;\n  private windowMs: number;\n\n  constructor(limit: number = 100, windowMs: number = 60000) {\n    this.limit = limit;\n    this.windowMs = windowMs;\n  }\n\n  isAllowed(clientId: string): boolean {\n    const now = Date.now();\n    \n    if (!this.requests.has(clientId)) {\n      this.requests.set(clientId, new Deque());\n    }\n\n    const deque = this.requests.get(clientId)!;\n\n    // Remove old requests outside window\n    while (!deque.isEmpty && deque.peekFirst()! < now - this.windowMs) {\n      deque.shift();\n    }\n\n    // Check limit\n    if (deque.size >= this.limit) {\n      return false;\n    }\n\n    // Add new request\n    deque.push(now);\n    return true;\n  }\n}\n\n// Usage in Express\nconst app = express();\nconst limiter = new RateLimiter(10, 60000); // 10 requests per minute\n\napp.use((req: Request, res: Response, next: Function) => {\n  const clientId = req.ip;\n\n  if (!limiter.isAllowed(clientId)) {\n    return res.status(429).json({ error: 'Too many requests' });\n  }\n\n  next();\n});\n\napp.get('/api/data', (req, res) => {\n  res.json({ data: 'Your data here' });\n});\n"})}),"\n",(0,s.jsx)(n.hr,{}),"\n",(0,s.jsx)(n.h2,{id:"nestjs-integration",children:"Nest.js Integration"}),"\n",(0,s.jsx)(n.h3,{id:"use-case-product-price-index-service",children:"Use Case: Product Price Index Service"}),"\n",(0,s.jsxs)(n.blockquote,{children:["\n",(0,s.jsxs)(n.p,{children:["Full working demo: ",(0,s.jsx)(n.a,{href:"https://stackblitz.com/github/zrwusa/dst-playgrounds/tree/main/apps/nestjs?file=src%2Fproduct%2Fservices%2Fproduct-price-index.service.ts&title=data-structure-typed%20%E2%80%94%20NestJS%20Product%20API",children:"StackBlitz NestJS Playground"})]}),"\n"]}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{className:"language-typescript",children:"import {\n  BadRequestException,\n  Injectable,\n  NotFoundException,\n} from '@nestjs/common';\n\nimport { Range, RedBlackTree } from 'data-structure-typed';\n\nexport interface Product {\n  id: string;\n  name: string;\n  price: number;\n  quantity: number;\n  category: string;\n  lastUpdated?: Date;\n}\n\ninterface CompositeKey {\n  price: number;\n  productId: string;\n}\n\nexport type TierName = 'budget' | 'mid-range' | 'premium';\n\n/**\n * Product Price Index Service using Red-Black Tree with Composite Keys\n *\n * \u2b50 Performance vs Alternatives:\n *\n * Operation          | RBTree(this approach) | Array     | HashMap + Sort\n * -------------------|-----------------------|-----------|---------------\n * Range Query        | O(log n + k)          | O(n)      | O(k log k)\n * Point Lookup       | O(1)                  | O(1)      | O(1)\n * Insert/Update      | O(log n)              | O(n)      | O(log n)\n * Sort by Price      | O(n)                  | O(n log n)| O(n log n)\n * Pagination         | O(log n + k)          | O(n log n)| O(n log n)\n * Rank/Percentile    | O(log n)              | O(n)      | O(n log n)\n */\n@Injectable()\nexport class ProductPriceIndexService {\n  private priceIndex: RedBlackTree<CompositeKey, Product>;\n  private idToKeyMap: Map<string, CompositeKey>;\n\n  constructor() {\n    this.priceIndex = new RedBlackTree([], {\n      comparator: (a: CompositeKey, b: CompositeKey) => {\n        const priceCmp = a.price - b.price;\n        if (priceCmp !== 0) return priceCmp;\n        return a.productId.localeCompare(b.productId);\n      },\n      enableOrderStatistic: true, // Enables getRank/getByRank/rangeByRank\n    });\n    this.idToKeyMap = new Map();\n  }\n\n  /** O(log n) */\n  addProduct(product: Product): Product {\n    if (this.idToKeyMap.has(product.id))\n      throw new BadRequestException(`Product ${product.id} already exists`);\n\n    product.lastUpdated = new Date();
1\n    const key: CompositeKey = { price: product.price, productId: product.id };\n    this.priceIndex.set(key, product);\n    this.idToKeyMap.set(product.id, key);\n    return product;\n  }\n\n  /** O(1) \u2014 HashMap lookup */\n  getProductById(productId: string): Product {\n    const key = this.idToKeyMap.get(productId);\n    if (key === undefined)\n      throw new NotFoundException(`Product ${productId} not found`);\n    return this.priceIndex.get(key)!;\n  }\n\n  /** O(log n + k) \u2014 directly returns values, no secondary lookup */\n  getProductsByPriceRange(minPrice: number, maxPrice: number): Product[] {\n    const range = new Range(\n      { price: minPrice, productId: '' },\n      { price: maxPrice, productId: '\\uffff' },\n      true,\n      true,\n    );\n    return this.priceIndex.rangeSearch(range, (n) => n.value!);\n  }\n\n  /** O(log n) \u2014 NavigableMap floor() */\n  getHighestPricedProductWithinBudget(maxBudget: number): Product | null {\n    const key: CompositeKey = { price: maxBudget, productId: '\\uffff' };\n    const floorKey = this.priceIndex.floor(key);\n    return floorKey ? this.priceIndex.get(floorKey)! : null;\n  }\n\n  /** O(n) \u2014 iterator protocol, one-liner */\n  getAllProductsSortedByPrice(): Product[] {\n    return [...this.priceIndex.values()];\n  }\n\n  /**\n   * O(n) for totalValue, O(log n) for min/max\n   * min/max use getLeftMost/getRightMost instead of full traversal\n   */\n  getStatistics() {\n    if (this.idToKeyMap.size === 0)\n      return { totalProducts: 0, priceRange: { min: 0, max: 0 }, averagePrice: 0, totalValue: 0 };\n\n    const minKey = this.priceIndex.getLeftMost();\n    const maxKey = this.priceIndex.getRightMost();\n\n    let totalValue = 0;\n    let totalProducts = 0;\n    for (const [, product] of this.priceIndex) {\n      totalValue += product.price * product.quantity;\n      totalProducts += product.quantity;\n    }\n\n    return {\n      totalProducts,\n      priceRange: { min: minKey?.price ?? 0, max: maxKey?.price ?? 0 },\n      averagePrice: totalValue / totalProducts,\n      totalValue,\n    };\n  }\n\n  // \u2500\u2500 Order-Statistic API (rank-based queries) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n  /** O(log n + pageSize) \u2014 rank-based pagination */\n  getProductsByPage(page: number, pageSize: number): Product[] {\n    const start = page * pageSize;\n    const end = Math.min(start + pageSize - 1, this.priceIndex.size - 1);\n    if (start >= this.priceIndex.size) return [];\n    const keys = this.priceIndex.rangeByRank(start, end);\n    return keys.map((key) => this.priceIndex.get(key)!);\n  }\n\n  /** O(log n) \u2014 what % of products are cheaper */\n  getPricePercentile(productId: string): number {\n    const key = this.idToKeyMap.get(productId);\n    if (!key) throw new NotFoundException(`Product ${productId} not found`);\n    return (this.priceIndex.getRank(key) / this.priceIndex.size) * 100;\n  }\n\n  /** O(log n) \u2014 median product */\n  getMedianProduct(): Product | null {\n    if (this.priceIndex.size === 0) return null;\n    const key = this.priceIndex.getByRank(Math.floor((this.priceIndex.size - 1) / 2));\n    return key ? this.priceIndex.get(key)! : null;\n  }\n\n  /** O(log n + k) \u2014 top N cheapest */\n  getTopNCheapest(n: number): Product[] {\n    const end = Math.min(n - 1, this.priceIndex.size - 1);\n    if (end < 0) return [];\n    return this.priceIndex.rangeByRank(0, end).map((key) => this.priceIndex.get(key)!);\n  }\n\n  /** O(log n + k) \u2014 top N most expensive */\n  getTopNExpensive(n: number): Product[] {\n    const size = this.priceIndex.size;\n    if (size === 0) return [];\n    const start = Math.max(size - n, 0);\n    return this.priceIndex.rangeByRank(start, size - 1)\n      .map((key) => this.priceIndex.get(key)!)\n      .reverse();\n  }\n\n  /** O(log n) \u2014 dynamic tier by percentile, no hardcoded price ranges */\n  getTierByPercentile(productId: string): TierName {\n    const pct = this.getPricePercentile(productId);\n    if (pct < 33) return 'budget';\n    if (pct < 66) return 'mid-range';\n    return 'premium';\n  }\n}\n"})}),"\n",(0,s.jsx)(n.h3,{id:"use-case-task-queue-controller",children:"Use Case: Task Queue Controller"}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{className:"language-typescript",children:"import { Controller, Post, Body, Get } from '@nestjs/common';\nimport { MaxPriorityQueue } from 'data-structure-typed';\n\nexport interface QueuedTask {\n  id: string;\n  action: string;\n  priority: number;\n  createdAt: Date;\n}\n\n@Controller('tasks')\nexport class TaskController {\n  private taskQueue = new MaxPriorityQueue<QueuedTask>([], {\n    comparator: (a, b) => a.priority - b.priority,\n  });\n\n  @Post('add')\n  addTask(@Body() task: QueuedTask): { success: boolean; queueSize: number } {\n    this.taskQueue.add(task);\n    return {\n      success: true,\n      queueSize: this.taskQueue.size,\n    };\n  }\n\n  @Post('process')\n  processNext(): { success: boolean; task: QueuedTask | null } {\n    const task = this.taskQueue.poll();\n    return {\n      success: !!task,\n      task: task || null,\n    };\n  }\n\n  @Get('queue-size')\n  getQueueSize(): { size: number } {\n    return { size: this.taskQueue.size };\n  }\n}\n"})}),"\n",(0,s.jsx)(n.hr,{}),"\n",(0,s.jsx)(n.h2,{id:"typescript-configuration",children:"TypeScript Configuration"}),"\n",(0,s.jsx)(n.h3,{id:"tsconfigjson-for-data-structure-typed",children:"tsconfig.json for data-structure-typed"}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{className:"language-json",children:'{\n  "compilerOptions": {\n    "target": "ES2020",\n    "module": "ES2020",\n    "lib": ["ES2020", "DOM"],\n    "strict": true,\n    "esModuleInterop": true,\n    "skipLibCheck": true,\n    "forceConsistentCasingInFileNames": true,\n    "resolveJsonModule": true,\n    "declaration": true,\n    "declarationMap": true,\n    "sourceMap": true\n  }\n}\n'})}),"\n",(0,s.jsx)(n.h3,{id:"packagejson-setup",children:"Package.json Setup"}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{className:"language-json",children:'{\n  "depen
1dencies": {\n    "data-structure-typed": "^latest"\n  },\n  "devDependencies": {\n    "typescript": "^5.0.0",\n    "@types/node": "^latest"\n  }\n}\n'})}),"\n",(0,s.jsx)(n.hr,{}),"\n",(0,s.jsx)(n.h2,{id:"import-patterns",children:"Import Patterns"}),"\n",(0,s.jsx)(n.h3,{id:"all-structures",children:"All Structures"}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{className:"language-typescript",children:"import {\n  // Trees\n  BST,\n  AVLTree,\n  RedBlackTree,\n  BSTNode,\n  TreeMultiMap,\n  \n  // Linear\n  Stack,\n  Queue,\n  Deque,\n  LinkedList,\n  SinglyLinkedList,\n  DoublyLinkedList,\n  \n  // Heap\n  Heap,\n  MinHeap,\n  MaxHeap,\n  MinPriorityQueue,\n  MaxPriorityQueue,\n  \n  // Special\n  Trie,\n  DirectedGraph,\n  UndirectedGraph,\n  \n  // Utilities\n  SegmentTree,\n  FenwickTree\n} from 'data-structure-typed';\n"})}),"\n",(0,s.jsx)(n.h3,{id:"module-systems",children:"Module Systems"}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{className:"language-js",children:"// ES Module (ESM)\nimport { RedBlackTree } from 'data-structure-typed';\n\n// CommonJS\nconst { RedBlackTree } = require('data-structure-typed');\n\n// TypeScript with full typing\nimport { RedBlackTree } from 'data-structure-typed/dist/esm/red-black-tree';\n\n// CDN (for browsers)\n<script src=\"https://cdn.jsdelivr.net/npm/data-structure-typed/dist/umd/data-structure-typed.min.js\"><\/script>\n<script>\n  const tree = new DataStructureTyped.RedBlackTree();\n<\/script>\n"})}),"\n",(0,s.jsx)(n.hr,{}),"\n",(0,s.jsx)(n.h2,{id:"common-integration-patterns",children:"Common Integration Patterns"}),"\n",(0,s.jsx)(n.h3,{id:"pattern-1-dependency-injection-nestjs",children:"Pattern 1: Dependency Injection (Nest.js)"}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{className:"language-typescript",children:"import { Module } from '@nestjs/common';\nimport { ProductInventoryService } from './product-inventory.service';\n\n@Module({\n  providers: [ProductInventoryService],\n  exports: [ProductInventoryService]\n})\nexport class ProductInventoryModule {}\n\n// Use in other services\n@Injectable()\nexport class OutherService {\n  constructor(private inventoryService: ProductInventoryService) {}\n\n  async addProduct(product: Product): Promise<void> {\n    this.inventoryService.addProduct(product);\n  }\n}\n"})}),"\n",(0,s.jsx)(n.h3,{id:"pattern-2-react-hooks",children:"Pattern 2: React Hooks"}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{className:"language-tsx",children:"import {useCallback, useRef, useState} from 'react';\nimport {RedBlackTree} from 'data-structure-typed';\n\nfunction useSortedList<T>(initialData: T[] = []) {\n  const treeRef = useRef(new RedBlackTree<number, T>(initialData));\n  const [, setUpdateTrigger] = useState({});\n\n  const add = useCallback((index: number, item: T) => {\n    treeRef.current.set(index, item);\n    setUpdateTrigger({});\n  }, []);\n\n  const remove = useCallback((index: number) => {\n    treeRef.current.delete(index);\n    setUpdateTrigger({});\n  }, []);\n\n  const getAll = useCallback(() => {\n    return [...treeRef.current.values()];\n  }, []);\n\n  return {add, remove, getAll};\n}\n\n// Usage\nfunction MyComponent() {\n  const {add, remove, getAll} = useSortedList<string>([]);\n\n  return (\n    <div>\n      <button onClick={() => add(1, 'Item 1')}>Add Item</button>\n      <ul>\n        {getAll().map((item, i) => (\n          <li key={i} onClick={() => remove(i)}>{item}</li>\n        ))}\n      </ul>\n    </div>\n  );\n}\n\nexport default MyComponent;\n"})}),"\n",(0,s.jsx)(n.hr,{}),"\n",(0,s.jsx)(n.h2,{id:"troubleshooting",children:"Troubleshooting"}),"\n",(0,s.jsx)(n.h3,{id:"issue-import-error",children:"Issue: Import Error"}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{className:"language-typescript",children:"// \u274c Wrong\nimport RedBlackTree from 'data-structure-typed';\n\n// \u2705 Correct\nimport { RedBlackTree } from 'data-structure-typed';\n"})}),"\n",(0,s.jsx)(n.h3,{id:"issue-type-not-found",children:"Issue: Type Not Found"}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{className:"language-shell",children:"// Make sure TypeScript configuration is correct\n// and you have the latest type definitions\nnpm update data-structure-typed\n"})}),"\n",(0,s.jsx)(n.h3,{id:"issue-performance-in-development",children:"Issue: Performance in Development"}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{className:"language-shell",children:"// Development mode is slower due to hot reload\n// Use production build for benchmarking:\nnpm run build\nNODE_ENV=production node your-app.js\n"})}),"\n",(0,s.jsx)(n.hr,{}),"\n",(0,s.jsxs)(n.p,{children:[(0,s.jsx)(n.strong,{children:"Need more examples?"})," Check ",(0,s.jsx)(n.a,{href:"/docs/guide/guides",children:"GUIDES.md"})," for more patterns."]}),"\n",(0,s.jsxs)(n.p,{children:[(0,s.jsx)(n.strong,{children:"Performance questions?"})," See ",(0,s.jsx)(n.a,{href:"/docs/guide/performance",children:"PERFORMANCE.md"}),"."]})]})}function l(e={}){const{wrapper:n}={...(0,o.R)(),...e.components};return n?(0,s.jsx)(n,{...e,children:(0,s.jsx)(u,{...e})}):u(e)}},8453(e,n,t){t.d(n,{R:()=>i,x:()=>a});var r=t(6540);const s={},o=r.createContext(s);function i(e){const n=r.useContext(o);return r.useMemo(function(){return"function"==typeof e?e(n):{...n,...e}},[n,e])}function a(e){let n;return n=e.disableParentContext?"function"==typeof e.components?e.components(s):e.components||s:i(e.components),r.createElement(o.Provider,{value:n},e.children)}}}]);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.