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

Saurabh Sharma @itsjzt

About: Fullstack Web developer.

Location:
Delhi, India
Joined:
Nov 13, 2017

Neat way to handle array and individual inputs in same function

Publish Date: Aug 31 '20
7 2

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

Comments 2 total

  • Tobias Nickel
    Tobias NickelAug 31, 2020

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

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

    but typescript don`t like it.

Add comment