0
\$\begingroup\$

When I write code, I tend to follow functional paradigms often. The main thing I try to do is use values returned from functions.

What I notice though, is I end up having a sort of function argument funnel where all the functions in the chain have the same arguments.


import fs from 'fs'
import path from 'path'

function dbFilePath(dbFilename: string) {
  const filePath = path.join(__dirname, "../", dbFilename + ".db")
  return filePath
}

export function fileData(dbFilename: string) {
  const file = dbFilePath(dbFilename)

  const fileContent = fs.readFileSync(
    file,
    "utf-8"
  );

  return fileContent
}

In this example code (which works fine), both functions have the same argument. This is an example of what I normally do.

What is best practice for structuring this piece of code?

\$\endgroup\$
3
  • \$\begingroup\$ Is the piece of code you posted something you'd actually used or heavily simplified? \$\endgroup\$ Commented Apr 19, 2023 at 10:10
  • 1
    \$\begingroup\$ A guide to Code Review for Stack Overflow users. \$\endgroup\$ Commented Apr 19, 2023 at 10:10
  • 1
    \$\begingroup\$ @Mast - this came directly from my source code. As it says, it works. \$\endgroup\$ Commented Apr 19, 2023 at 10:22

1 Answer 1

1
\$\begingroup\$

You can create a function type which will accept only 1 parameter like this

type AccpetString<T> = (s: string) => T;

Then you need to save your functions in variables with type AccpetString<T> like this:

const dbFilePath:AccpetString<string> = dbFilename => {
  const filePath = path.join(__dirname, '../', dbFilename + '.db');

  return filePath;
}

or like this:

export const fileData:AccpetString<string> = function(dbFilename) {
  const file = dbFilePath(dbFilename);

  const fileContent = fs.readFileSync(
    file,
    'utf-8'
  );

  return fileContent
}

Now you don't need to specify the type of dbFilename in your functions

If your functions returns the string always, then we can declare a new type like this

type AccpetStringReturnString = AccpetString<string>

and rewrite your functions like this:

const dbFilePath:AccpetStringReturnString = dbFilename => {
  const filePath = path.join(__dirname, '../', dbFilename + '.db');

  return filePath;
}

or like this:

export const fileData:AccpetStringReturnString = function(dbFilename) {
  const file = dbFilePath(dbFilename);

  const fileContent = fs.readFileSync(
    file,
    'utf-8'
  );

  return fileContent
}

Playground

\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.