A generic, type-safe Doubly Linked List data structure implementation in TypeScript.
- Type-Safe: Uses TypeScript generics (
List<T>
) for strong type checking. - Standard Operations: Provides common list operations (
push
,getData
,removeByData
,removeByIndex
,findIndex
,toArray
,isEmpty
). - Efficient: Implements optimizations like searching from head or tail in
getData
andremoveByIndex
. - Well-Tested: Includes a comprehensive test suite.
npm install doubly-linked-list-typescript
# or
yarn add doubly-linked-list-typescript
import { List } from 'doubly-linked-list-typescript';
// Create a list to store numbers
const numberList = new List<number>();
numberList.push(10);
numberList.push(20);
numberList.push(30);
console.log(numberList.toArray()); // Output: [10, 20, 30]
console.log(numberList.length); // Output: 3
// Create a list to store custom objects
interface User {
id: number;
name: string;
}
const userList = new List<User>();
userList.push({ id: 1, name: 'Alice' });
userList.push({ id: 2, name: 'Bob' });
console.log(userList.getData(0)); // Output: { id: 1, name: 'Alice' }
const removedUser = userList.removeByIndex(1); // Remove Bob
console.log(removedUser); // Output: { id: 2, name: 'Bob' }
console.log(userList.length); // Output: 1
Creates a new empty list that can hold elements of type T
.
Returns the number of elements in the list. (Read-only)
Returns the first node in the list, or null
if the list is empty. (Read-only)
Returns the last node in the list, or null
if the list is empty. (Read-only)
Adds an element to the end (tail) of the list.
Returns the data of the element at the specified index
. Returns null
if the index is out of bounds. Optimized to search from the head or tail, whichever is closer (O(n)).
Searches for the first occurrence of the given data
in the list and returns its index. Returns -1
if the data is not found (O(n)). Uses strict equality (===
) for comparison.
Removes the element at the specified index
and returns its data. Returns null
if the index is out of bounds. Optimized to search from the head or tail (O(n)).
Removes the first occurrence of the given data
from the list and returns the removed data. Returns null
if the data is not found (O(n)). Uses strict equality (===
) for comparison.
Returns an array containing all the data elements in the list, in order from head to tail (O(n)).
Returns true
if the list contains no elements, false
otherwise (O(1)).
- Clone the repository:
git clone <https://github.com/bdspen/doubly-linked-list-typescript> cd doubly-linked-list-typescript
- Install dependencies:
npm install # or yarn install
- Build: Compile TypeScript to JavaScript:
npm run build
- Lint: Check for code style issues:
npm run lint
- Test: Run the test suite:
(This runs tests on the compiled code in
npm test
dist/
)
Contributions are welcome! Please open an issue or submit a pull request.