how can I import array prototype functions into my project

Viewed 111

So I have written a bunch of functions on arrays to use throughout my project. My functions are something simple like this

Array.prototype.mySort == function(){
    return this.sort((a,b) => a.text < b.text ? -1 : 1)
}

I have them all written in a separate file called array-helper-functions

Now I want to be able to use them in other files like this

const transformedArray = myArray.map(something).mySort().filter(somethingElse)

how could I export them in source file and import them ?

1 Answers

If your JS runs on NodeJS, then you can create a function like this:

function initializeArrayFunctions() {
    Array.prototype.mySort = function(){
        return this.sort((a,b) => a.text < b.text ? -1 : 1)
    }
}

export default initializeArrayFunctions;

and then you can import it and call it in the other file. If your JS is running in the browser, then you will need a script tag with its src being the correct path to the file you intend to load.

Related