Return the central character if the number of characters is odd and if it is even to return the 2 central characters

0

What must return is to execute is the central character if the number of characters is odd and if it is even to return the 2 central characters, what should return is "is".

(function getMiddle(s)
 {
 var name = s;
 var name2 = s.length;
 if(name2%2 === 0){
  var valor1= (name2/2)-1; 
  var valor2=(name2/2)+1;
return name.slice(valor1,valor2);
}else{
  var valor1=(name2-1)/2; 
  var valor2=(name2+1)/2;
 return name.slice(valor1,valor2);
 }
}("test"));
    
asked by user889 01.05.2018 в 23:08
source

1 answer

2

According to the Mozilla Developer Network, functions in parentheses are known as self-running functions or in English as Immediately Invoked Function Expression (IIFE)

The way to use the function in Stack Snippet is to assign to a variable the self-executing function and then do what it is required to do with this variable. For simplicity, the following example shows the result in the console.

Note that the result is es

var salida = (function getMiddle(s)
 {
 var name = s;
 var name2 = s.length;
 if(name2%2 === 0){
  var valor1= (name2/2)-1; 
  var valor2=(name2/2)+1;
return name.slice(valor1,valor2);
}else{
  var valor1=(name2-1)/2; 
  var valor2=(name2+1)/2;
 return name.slice(valor1,valor2);
 }
}("test"));

console.info(salida)

NOTE: A short form of doing the same thing is the following:

function getMiddle(texto){
  return (texto.length % 2)? texto.substr(texto.length/2,1):texto.substr(texto.length/2 - 1,2);
}

console.info(getMiddle("test"));
    
answered by 02.05.2018 / 04:10
source