Skip to content

lagden/condition

Repository files navigation

Condition

NPM version Node.js CI Coverage Status

Create conditional to validate data.

Install

$ npm i @tadashi/condition

Operators

Operator Symbol Description
eq === Two values are equal
ne !== Two values are not equal
gt > The first value is greater than the second value
ge >= The first value is greater than or equal to the second value
lt < The first value is less than the second value
le <= The first value is less than or equal to the second value
intersection There is an intersection between two arrays
difference There is a difference between two arrays
arrayEquals = Two arrays are equal
regex - The value matches a regular expression pattern
length - The length of a value satisfies a comparison
assigned - The value was assigned

Usage

See example below.

import 'condition' from '@tadashi/condition'

const data = {
  age: 65,
  gender: 'F',
  city: 'São Paulo',
  country: 'Brazil',
  phone: '(11) 988889999',
  hasCar: true,
  colors: ['red', 'blue'],
}

const conditions = [
  {
    join_operator: 'and',
    args: [
      {
        field: 'gender',
        operator: 'eq',
        value: 'F',
      }, {
        field: 'age',
        operator: 'gt',
        value: 21,
      }, {
        field: 'phone',
        operator: 'regex',
        value: /\(\d{2}\)\s(\d{8,9})/i,
      }, {
        join_operator: 'or',
        args: [
          {
            field: 'city',
            operator: 'assigned',
            value: false,
          }, {
            field: 'country',
            operator: 'intersection',
            value: ['Japan', 'Brazil'],
          },
        ],
      }, {
        field: 'hasCar',
        operator: 'eq',
        value: true,
      }, {
        field: 'colors',
        operator: 'intersection',
        value: ['blue', 'green', 123],
      }, {
        field: 'colors',
        operator: 'arrayEquals',
        value: ['red', 'blue'],
      },
    ],
  },
]

const isValid = condition(conditions)
isValid(data) // => true

Donate ❤️

BTC: bc1q7famhuj5f25n6qvlm3sssnymk2qpxrfwpyq7g4

License

MIT © Thiago Lagden