DEV Community

Cover image for JS Number extensions with Metho
Jon Randy 🎖️
Jon Randy 🎖️

Posted on • Updated on

JS Number extensions with Metho

Following on from the previous introduction to Metho, I decided to throw together metho-number as a real example of what it allows you to make.

Ruby developers may well recognise some of these number methods:

import {
  hex, bin, base, even, odd, ceil, floor, round,
  next, pred, gcd, chr, to, of, times, abs
} from 'metho-number'

254[hex]         // 'fe'
23[bin]          // '10111'
45[base(13)]     // '36'
12[even]         // true
218[odd]         // false
36.2[ceil]       // 37
18.9[floor]      // 18
41.5[round]      // 42
3[next]          // 4
8[pred]          // 7
36[gcd(81)]      // 9 (greatest common divisor)
65[chr]          // 'A'
(-8)[abs]        // 8

5[to(2)]             // [5, 4, 3, 2]
2[to(8, {step: 2})]  // [2, 4, 6, 8]

3[of('x')]              // ['x', 'x', 'x']
3[of(<div>text</div>)]  // Works just fine in JSX

3[times('Go!')]  // 'Go!Go!Go!'
10[times(()=>alert('Hello'))]  // run the function 10 times
Enter fullscreen mode Exit fullscreen mode

All of these extensions to the native Number type should be safe to use in any project.

What do you think? What would you add? Useful library or interesting toy? Would you like to see perhaps metho-string and metho-array?

GitHub logo jonrandy / metho

A new method for methods

GitHub logo jonrandy / metho-number

Number prototype extensions

Top comments (1)

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Bringing destructuring into the mix:

const {[bin]: binary, [hex]: hexidecimal, [base(8)]: octal} = 16

console.log(binary) // "10000"
console.log(hexidecimal) // "10"
console.log(octal) // "20"
Enter fullscreen mode Exit fullscreen mode