1.0.1 • Published 4 years ago

condition-handler v1.0.1

Weekly downloads
4
License
MIT
Repository
github
Last release
4 years ago

condition-handler

NPM minzipped size downloads license
The handler of conditions.

Installation

npm i condition-handler
# or
yarn add condition-handler

Or you can use minified file.

<!doctype html>
<html>
  <head>
    <script src="conditionHandler.min.js"></script>
  </head>
  <body>
    <script>
      console.log(conditionHandler('!', true))
    </script>
  </body>
</html>

Using

You can use any operators from the list
! && || === == !== != > >= < <= ( )
It works the same as if operator from JavaScript.

conditionHandler([1]) // 1 === 1

conditionHandler([1, '&&', 2]) // 1 && 2 === 2

conditionHandler([1, '&&', 0]) // 1 && 0 === 0

conditionHandler([1, '||', 0]) // 1 || 0 === 1

conditionHandler(['!', 1, '||', 0]) // !1 || 0 === 0

conditionHandler([1, '>', 2]) // 1 > 2 === false

conditionHandler([2, '>=', 1]) // 2 >= 1 === true

You can use a plugin to handle non-operator argument.

const obj = {
  test1: true,
  test2: false,
  test: {
    field1: 1,
    field2: 0
  }
}

function plugin (condition) {
  if (typeof condition === 'string') {
    const fields = condition.split('.')
    condition = obj
    for (let i = 0; i < fields.length; i++) {
      condition = condition[fields[i]]
    }
  }
  return condition
}

conditionHandler(['test1', '&&', 'test.field2'], plugin)
// obj.test1 && obj.test.field2 === 0

Issues

If you find a bug, please file an issue on GitHub
issues

stars watchers