-1

I want to create tools class/function in nextjs

I have 2 ways for this.

With static class:

class Tools {
    static titleCase(value: string) {
        return value.charAt(0).toUpperCase() + value.slice(1).toLowerCase();
    }
}

export default Tools

With use function:

export default function Tools(){
    function titleCase(value: string) {
        return value.charAt(0).toUpperCase() + value.slice(1).toLowerCase();
    }

    return { titleCase }
}

And here is my question:

1- Which is better?

2- What is difference between these?

Rez Mohsnei
  • 187
  • 3
  • 14
  • 1
    Please revise your post title to ask a clear, specific question. Don't tack on tags. See [ask]. – isherwood Jan 18 '22 at 21:25
  • 2
    Your second snippet is not static at all. It requires a call like `const t = Tools(); t.titleCase(…)` whereas for your first it's just `Tools.titleCase(…)` – Bergi Jan 18 '22 at 21:25
  • 2
    See also [ES6 modules: Export single class of static methods OR multiple individual methods](https://stackoverflow.com/q/29893591/1048572) – Bergi Jan 18 '22 at 21:27

1 Answers1

1

Neither. The better solution for static utility functions is to use named exports:

// tool.js:
export function titleCase(value: string) {
    return value.charAt(0).toUpperCase() + value.slice(1).toLowerCase();
}

Shorter, no unnecessary intermediate objects, and good for tree-shaking.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375