0

I would like to create an npm package for common functions that I use and are not part of javascript , but I dont know how can I create them to use them as methods, let me explain myself

For example I want to use a function like

let reverseString = (string) => string.split('').reverse().join('');

For sure I could use it like reverseString(''somethinghere')

But I would like to use it like 'somethinghere'.reverseString()

Thank you so much in advance.....

Daniel
  • 15
  • 4
  • No need to create a module, just use `module.exports`/`require()` or `import`/`export` (i.e. put the functions in a .js file, export them in there, then import the file elsewhere) –  Sep 14 '21 at 19:49

2 Answers2

1

Oh. Its not at all related to npm package. You are talking about JS prototypes. Basically you want to add custom function in String class. Not a good idea to do but still if you want you can do

String.prototype.reverseString = function (str) {
    return str.split('').reverse().join('');
  }
Sachin
  • 2,912
  • 16
  • 25
0

Create a .js file with your method:

module.exports = {
  reverseString: (string) => string.split('').reverse().join('')
}

Then elsewhere, use it with require()

const somethinghere = require('myfile.js')

somethinghere.reverseString('hello')
Timur
  • 1,682
  • 1
  • 4
  • 11