Socket
Book a DemoInstallSign in
Socket

generate-radix-tree

Package Overview
Dependencies
Maintainers
1
Versions
4
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

generate-radix-tree

Generates a function that uses a radix tree to match which pattern fits the input

latest
Source
npmnpm
Version
1.0.3
Version published
Maintainers
1
Created
Source

generate-radix-tree

Generates a function that uses a radix tree to match which pattern fits the input

npm install generate-radix-tree

Usage

const gentree = require('generate-radix-tree')

const match = gentree([
  {match: 'hello'},
  {match: 'world'},
  {match: 'hello world'}
])

console.log(match('hello')) // returns {match: 'hello'} as it matches
console.log(match('hello world')) // returns {match: 'hello world'}
console.log(match('hey')) // returns null

The returned match function is code generated based in the input to make as few comparisons as possible to find the pattern that matches.

You can view the generated source code by calling toString() on the function

console.log(match.toString())

Dynamic matches

If you want to match against a dynamic pattern use a function. This function must set fn.pointer to the end index in the string it matches.

For example

const match = gentree([
  {match: ['hello', any, 'world']},
  {match: 'hello world'}
])

console.log(match('hello world')) // return {match: 'hello world'}
console.log(match('hello_world')) // return {match: ['hello', any, 'world]}

// match any char in str at ptr
function any (str, ptr) {
  if (str.length > ptr) {
    // more chars, we match
    // set any.pointer to where we matched to
    any.pointer = ptr + 1
    return true
  }
  return false
}

The static patterns always have preference to the dynamic ones

License

MIT

FAQs

Package last updated on 06 Sep 2018

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts