DEV Community

Cover image for Neat way to handle array and individual inputs in same function
Saurabh Sharma
Saurabh Sharma

Posted on

6

Neat way to handle array and individual inputs in same function

Lets say we need to make a function doSomething. we need to do it in a way so that it can handle both arguments: (1) a string and (2) an array of strings.

To achieve that previously I used to do something like this:

function doSomething(strs) {
  function _doSomething(str) {
    // some mysterious stuff happening here
    console.log(str)
  }

  if (Array.isArray(strs)) {
      return strs.map(str => _doSomething(str))
  } else {
      return _doSomething(strs)
  }
}

doSomething(["hello", "world"])
doSomething("hello")
Enter fullscreen mode Exit fullscreen mode

now since I learned recursion I do this:

function doSomething(strs) {
  if (Array.isArray(strs)) {
      return strs.map(str => doSomething(str))
  } else {
      console.log(strs);
  }
}

doSomething(["hello", "world"])
doSomething("hello")
Enter fullscreen mode Exit fullscreen mode

cover Photo by pepe nero on Unsplash

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (2)

Collapse
 
bias profile image
Tobias Nickel

for a while i added something like this to my functions:

if (!Array.isArray(arg)) arg = [arg];

but typescript don`t like it.

Collapse
 
itsjzt profile image
Saurabh Sharma

Typescript doesnt know anything 😑

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay