purify-int

Verify that an input value is a JavaScript integer and replace as needed

Usage no npm install needed!

<script type="module">
  import purifyInt from 'https://cdn.skypack.dev/purify-int';
</script>

README

Purify Int

forthebadge

License: MIT github: version github: last-commit npm: version npm: downloads

How To Use

  • Run npm i purify-int
  • Include const Purify = require('purify-int')

Function Guide

asInt()

  • Purify input to valid Integer:
let cleansed = Purify.asInt('42')
console.log(cleansed) // output: 42
let cleansed = Purify.asInt('words')
console.log(cleansed) // output: 0

asIntIn()

  • Purify input to valid Integer with input non-Integer as fallback:
let cleansed = Purify.asIntIn('42')
console.log(cleansed) // output: 42
let cleansed = Purify.asIntIn('words')
console.log(cleansed) // output: 'words'

asIntR()

  • Purify input to valid Integer with randomized fallback:
let cleansed = Purify.asIntR('42')
console.log(cleansed) // output: 42
let cleansed = Purify.asIntR('words')
console.log(cleansed) // output: random integer between 1 and current unix time in ms

asIntF()

  • Purify input to valid Integer with optional second Integer-like arg as fallback:
let cleansed = Purify.asIntF('42', 5)
console.log(cleansed) // output: 42
let cleansed = Purify.asIntF('words', 5)
console.log(cleansed) // output: 5
let cleansed = Purify.asIntF('words', '5')
console.log(cleansed) // output: 5
let cleansed = Purify.asIntF('words', 'more words')
console.log(cleansed) // output: 0

asIntN()

  • Purify input to valid Integer with null as fallback:
let cleansed = Purify.asIntN('42')
console.log(cleansed) // output: 42
let cleansed = Purify.asIntN('words')
console.log(cleansed) // output: null

asArrayInt()

  • Flags are optional. Valid flags are:
    • R : Use random number as fallback
    • N : Use null as fallback
    • K : Use input non-Integer as fallback
  • Purify input to valid array of Integers:
let cleansed = Purify.asArrayInt(['42', 'words']) // flag is optional
console.log(cleansed) // output: [42, 0]
let cleansed = Purify.asArrayInt(['42', 'words'], 'R')
console.log(cleansed) // output: [42, random integer as above]
let cleansed = Purify.asArrayInt(['42', 'words'], 'N')
console.log(cleansed) // output: [42, null]
let cleansed = Purify.asArrayInt(['42', 'words'], 'K')
console.log(cleansed) // output: [42, 'words']