type-reverse
🦄 Lightweight reverse utility around strings, arrays, numbers and more.
Install
$ npm install --save type-reverse
Usage
const reverse = require('type-reverse')
or...
import reverse from 'type-reverse'
API
reverse( input[, options][, callback] )
Params
input
{String|Number|Array|Set}options
{?Object}callback
{?Function}returns
{*}
reverse('pizza')
Works with numbers too.
reverse(1234)
Reversing arrays...
When JavaScript's Array#reverse method is used, the original array is mutated, as in, the indexes of the elements are changed. On the other hand, this utility adopts the non-destructive array reversal method, which means the reverse()
function doesn't mutate the array; it just returns the reversed array and still maintains the indexes of the elements in the original array.
native reverse...
const arr = [1, 2, 3]
arr.reverse()
Oops, we lost the indexes of elements in the initial array...
console.log(arr)
vs...
🦄 to the rescue...
const arr = [1, 2, 3]
reverse(arr)
Yay! arr
is not mutated. The indexes of its elements are still maintained...
console.log(arr)
Sets
If you've been wondering how to reverse Sets in JavaScript, here's it! The core reverse
function can take in a Set
as the input and then return the reversed Set
...
const set = new Set([5, 4, 3, 4, 5])
reverse(set)
options
options
is the second parameter to the function call and it is an object with two available properties. It can also take in a falsy value which would implicity get converted to an empty object.
invert: {String}
This property defaults to index
and applies to strings and numbers only.
reverse(, {
invert: '[index|word|sign]'
})
-
index
- interchanges the indexes of characters in the input...
reverse(12345, { invert: 'index' })
reverse('of... unicorns', { invert: 'index' })
-
sign
- inverts the sign in a number...
reverse(1234, { invert: 'sign' })
-
word
- swaps the location of words in a string...
reverse('of... unicorns', { invert: 'word' })
preserveZeros: {Boolean}
This property defaults to true
. It specifies whether to enforce preceding zeros in the result of a number that contains trailing zeros. See #3 for more info. Note that the result gets converted to a string. Disabling it would look like this...
reverse(240, { preserveZeros: false })
callback: {Function}
The callback takes in a function with two optional parameters that represent input
and result
respectively.
input
- the initial input that was passed into the functionresult
- the output from reversing the input
const text = 'dog'
reverse(text, null, function(intitial, result) {
return intitial + ' was changed to ' + result
})
Limits
Did you just try to reverse a reaally huge number? Unfortunately, this utility doesn't support very large numbers. Trying to do so with this utility would throw a TypeError.
Author
Olaolu Olawuyi
License
MIT © Olaolu Olawuyi