Home > Software design >  Create a package or a function that behaves as a method?
Create a package or a function that behaves as a method?

Time:09-17

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.....

CodePudding user response:

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('');
  }

CodePudding user response:

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')
  • Related