newick
v3.0.1
Published
A Newick tree parser
Readme
newick
A lightweight and TypeScript-friendly library to parse, manipulate, and serialize trees in the Newick format. Includes an OOP interface for clean and composable workflows.
✨ Features
- Parse and serialize Newick trees
- Traverse and map with callbacks
- Normalize branch lengths
- Compare and clone trees
- Type-safe API (written in TypeScript)
📦 Installation
npm install newickOr via yarn:
yarn add newick🔧 Usage
import { Newick } from 'newick';
const input = '(A:0.1,B:0.2)Root;';
const tree = new Newick(input);
console.log(tree.getRoot()); // "Root"
tree.map(node => {
node.name = node.name?.toUpperCase();
return node;
});
console.log(tree.serialize()); // "(A:0.1,B:0.2)ROOT"
console.log(tree.toString()); // Same as serialize📚 API
🌳 Newick class
new Newick(data: string | NewickNode)Creates a new Newick instance from a Newick string or a tree object.
getRoot(): string | nullReturns the name of the root node, or null if not present.
dfs(callback?: (node: NewickNode) => NewickNode): Record<string, number>Performs a depth-first traversal of the tree.
callback(optional): applied to each node.- Returns a map of node names to branch lengths.
map(callback: (node: NewickNode) => NewickNode): voidApplies a callback to each node in-place, mutating the tree.
normalize(): NewickNodeNormalizes all branch lengths so they sum to 1. Returns the normalized tree.
serialize(): stringSerializes the tree to a valid Newick-format string without a trailing semicolon.
toString(): stringAlias for serialize().
clone(): NewickCreates a deep clone of the current tree.
equal(anotherTree: Newick): booleanReturns true if another Newick instance is structurally equal (case-insensitive).
parse(input: string): NewickNodeParses a Newick string into a NewickNode tree object.
🧪 Testing
npm testTests are written using Jest.
📄 License
MIT © Kir Tribunsky
