Match numbers by interval

Turn on the interval option to let a pattern value match a range of numbers, such as >10 or [10,20].

Use this when a pattern should match a range of numbers, such as an amount over a threshold. With the interval option on, a pattern value written with an operator or as a range is an interval, and a query's value matches it when the value is a number in it.

const patrun = require('patrun')

const pm = patrun({ interval: true })
  .add({ x: '<10' }, 'low')
  .add({ x: '[10,20]' }, 'mid')
  .add({ x: '>20' }, 'high')

pm.find({ x: 5 }) // → 'low'
pm.find({ x: 15 }) // → 'mid'
pm.find({ x: '42' }) // → 'high'
pm.find({ x: 'abc' }) // → null

The forms an interval takes are in How a match is chosen: >10, <=10, =10, [10,20], (10,20), 10..20, >=10&<20, and <10||>20, among them.

When two intervals for the same key both match, the narrower one wins, whichever was added first:

const patrun = require('patrun')

const pm = patrun({ interval: true })
  .add({ x: '>10' }, 'OVER-10')
  .add({ x: '[10,20]' }, 'TEN-TO-TWENTY')
  .add({ x: '[14,16]' }, 'AROUND-15')
  .add({ x: '=15' }, 'FIFTEEN')

pm.find({ x: 15 }) // → 'FIFTEEN'
pm.find({ x: 16 }) // → 'AROUND-15'
pm.find({ x: 18 }) // → 'TEN-TO-TWENTY'
pm.find({ x: 30 }) // → 'OVER-10'

In Go #

Set Options.Interval. A Go query's values are strings, and a value matches an interval when the whole string is a number in it:

pm := patrun.New(patrun.Options{Interval: true})
pm.Add(map[string]string{"x": "<10"}, s("low"))
pm.Add(map[string]string{"x": "[10,20]"}, s("mid"))
pm.Add(map[string]string{"x": ">20"}, s("high"))

pm.Find(map[string]string{"x": "5"})  // → "low"
pm.Find(map[string]string{"x": "15"}) // → "mid"
pm.Find(map[string]string{"x": "42"}) // → "high"

What to watch for #

A number on its own, such as 10, is an exact value, matched as text: write =10 to match the number. A value such as '15px' or '15 ' is no number, and matches no interval.

An exact value beats an interval, and an interval beats the star. interval can be on together with gex, and then every glob beats every interval: 15 matches both 1* and [10,20], and the glob wins.

[10,20], 10..20, and >=10&<=20 are one pattern. Adding it again in any of its spellings replaces its data, and remove, get, and list find it by any of them.

This page describes patrun 9.0.0 for JavaScript and 0.4.0 for Go. Edit this page · This page as Markdown