CoffeeScript - Splat

Nos capítulos anteriores, vimos como definir uma função e invocar uma função e passar argumentos para ela. Em geral, podemos passar um número fixo de argumentos para uma função. Durante a programação, podemos enfrentar situações em que precisamos passar argumentos variáveis ​​para essas funções. Em JavaScript, usamos objetos para aceitar um número variável de argumentos para uma função.

CoffeeScript fornece um recurso chamado splatspara passar vários argumentos para funções. Usamos splats em funções colocando três pontos após o nome do argumento e, é denotado por...

Sintaxe

A seguir, é fornecida a sintaxe para aceitar vários argumentos em uma função usando splats.

my_function = (arguments...)->
   ............
   ............
   ............

Exemplo

A seguir está um exemplo de aceitação de vários argumentos em uma função, usando splats. Aqui definimos uma função chamadaindian_team()usando indicadores. Estamos chamando essa função três vezes e estamos passando 4 jogadores, 6 jogadores e time completo simultaneamente, a cada vez que a chamamos. Como usamos splats na definição da função, ela aceita um número variável de argumentos cada vez que a chamamos. Salve este código em um arquivo com o nomesplats_definition.coffee

indian_team = (first, second, others...) ->
  Captain = first
  WiseCaptain = second
  team  = others
  console.log "Captain: " +Captain
  console.log "Wise captain: " +WiseCaptain
  console.log "Other team members: " +team

#Passing 4 arguments
console.log "############## Four Players ############"
indian_team "Mahendra Singh Dhoni", "Virat Kohli", "Shikhar Dhawan", "Rohit Sharma"

#Passing 6 arguments
console.log "############## Six Players ############"
indian_team "Mahendra Singh Dhoni", "Virat Kohli", "Shikhar Dhawan", "Rohit Sharma", "Gurkeerat Singh Mann", "Rishi Dhawan"
  
#Passing full squad
console.log "############## Full squad #############"
indian_team "Mahendra Singh Dhoni", "Virat Kohli", "Shikhar Dhawan", "Rohit Sharma", "Gurkeerat Singh Mann", "Rishi Dhawan", "Ravindra Jadeja", "Axar Patel", "Jasprit Bumrah", "Umesh Yadav", "Harbhajan Singh", "Ashish Nehra", "Hardik Pandya", "Suresh Raina", "Yuvraj Singh", "Ajinkya Rahane"

Abra o command prompt e compilar o arquivo .coffee conforme mostrado abaixo.

c:\> coffee -c splats_definition.coffee

Na compilação, ele fornece o seguinte JavaScript.

// Generated by CoffeeScript 1.10.0
(function() {
  var indian_team,
    slice = [].slice;

  indian_team = function() {
    var Captain, WiseCaptain, first, others, second, team;
    first = arguments[0], second = arguments[1], others = 3 <= arguments.length ? slice.call(arguments, 2) : [];
    Captain = first;
    WiseCaptain = second;
    team = others;
    console.log("Captain: " + Captain);
    console.log("Wise captain: " + WiseCaptain);
    return console.log("Other team members: " + team);
  };

  console.log("############## Four Players ############");

  indian_team("Mahendra Singh Dhoni", "Virat Kohli", "Shikhar Dhawan", "Rohit Sharma");

  console.log("############## Six Players ############");

  indian_team("Mahendra Singh Dhoni", "Virat Kohli", "Shikhar Dhawan", "Rohit Sharma", "Gurkeerat Singh Mann", "Rishi Dhawan");

  console.log("############## Full squad #############");

  indian_team("Mahendra Singh Dhoni", "Virat Kohli", "Shikhar Dhawan", "Rohit Sharma", "Gurkeerat Singh Mann", "Rishi Dhawan", "Ravindra Jadeja", "Axar Patel", "Jasprit Bumrah", "Umesh Yadav", "Harbhajan Singh", "Ashish Nehra", "Hardik Pandya", "Suresh Raina", "Yuvraj Singh", "Ajinkya Rahane");

}).call(this);

Agora, abra o command prompt novamente e execute o arquivo CoffeeScript conforme mostrado abaixo.

c:\> coffee splats_definition.coffee

Ao ser executado, o arquivo CoffeeScript produz a seguinte saída.

############## Four Players ############
Captain: Mahendra Singh Dhoni
Wise captain: Virat Kohli
Other team members: Shikhar Dhawan,Rohit Sharma
############## Six Players ############
Captain: Mahendra Singh Dhoni
Wise captain: Virat Kohli
Other team members: Shikhar Dhawan,Rohit Sharma,Gurkeerat Singh Mann,Rishi Dhawan
############## Full squad #############
Captain: Mahendra Singh Dhoni
Wise captain: Virat Kohli
Other team members: Shikhar Dhawan,Rohit Sharma,Gurkeerat Singh Mann,Rishi Dhawan,Ravindra Jadeja,Axar Patel,Jasprit Bumrah,Umesh Yadav,Harbhajan Singh,Ashish Nehra,Hardik Pandya,Suresh Raina,Yuvraj Singh,Ajinkya Rahane

Chamando funções usando Splats

Também podemos chamar uma função usando splats. Para isso, temos que criar um array contendo os elementos que precisamos passar para a função, e temos que chamar a função passando o array com o sufixo de três pontos como mostrado abaixo.

my_function values...

Exemplo

A seguir está um exemplo de chamada de uma função usando splats. Salve este código em um arquivo com o nomesplats_call.coffee

indian_team = (first, second, others...) ->
  Captain = first
  WiseCaptain = second
  team  = others
  console.log "Captain: " +Captain
  console.log "Wise captain: " +WiseCaptain
  console.log "Other team members: " +team

squad = [
   "Mahendra Singh Dhoni"
   "Virat Kohli"
   "Shikhar Dhawan"
   "Rohit Sharma"   
   "Gurkeerat Singh Mann"
   "Rishi Dhawan"
   "R Ashwin"
   "Ravindra Jadeja"
   "Axar Patel"
   "Jasprit Bumrah"
   "Umesh Yadav"
   "Harbhajan Singh"
   "Ashish Nehra"
   "Hardik Pandya"
   "Suresh Raina"
   "Yuvraj Singh"
   "Ajinkya Rahane"
 ]

indian_team squad...

Abra o command prompt e compilar o arquivo .coffee conforme mostrado abaixo.

c:\> coffee -c splats_call.coffee

Na compilação, ele fornece o seguinte JavaScript.

// Generated by CoffeeScript 1.10.0
(function() {
  var indian_team, squad,
    slice = [].slice;

  indian_team = function() {
    var Captain, WiseCaptain, first, others, second, team;
    first = arguments[0], second = arguments[1], others = 3 <= arguments.length ? slice.call(arguments, 2) : [];
    Captain = first;
    WiseCaptain = second;
    team = others;
    console.log("Captain: " + Captain);
    console.log("Wise captain: " + WiseCaptain);
    return console.log("Other team members: " + team);
  };

  squad = ["Mahendra Singh Dhoni", "Virat Kohli", "Shikhar Dhawan", "Rohit Sharma", "Gurkeerat Singh Mann", "Rishi Dhawan", "R Ashwin", "Ravindra Jadeja", "Axar Patel", "Jasprit Bumrah", "Umesh Yadav", "Harbhajan Singh", "Ashish Nehra", "Hardik Pandya", "Suresh Raina", "Yuvraj Singh", "Ajinkya Rahane"];

  indian_team.apply(null, squad);

}).call(this);

Agora, abra o command prompt novamente e execute o arquivo CoffeeScript conforme mostrado abaixo.

c:\> coffee splats_call.coffee

Ao ser executado, o arquivo CoffeeScript produz a seguinte saída.

Captain: Mahendra Singh Dhoni
Wise captain: Virat Kohli
Other team members: Shikhar Dhawan,Rohit Sharma,Gurkeerat Singh Mann,Rishi Dhawan,R Ashwin,Ravindra Jadeja,Axar Patel,Jasprit Bumrah,Umesh Yadav,Harbhajan Singh,Ashish Nehra,Hardik Pandya,Suresh Raina,Yuvraj Singh,Ajinkya Rahane

Splats com um argumento de cauda

Também podemos passar argumentos de cauda para splats. No exemplo abaixo, passamos um argumento de cauda chamadolastapós o splat. Salve este exemplo em um arquivo com o nometailing_arguments.coffee

indian_team = (first, second, others..., last) ->
  Captain = first
  WiseCaptain = second
  team  = others
  Wicketkeeper =last
  console.log "Captain: " +Captain
  console.log "Wise captain: " +WiseCaptain
  console.log "Wicket keeper is:"+last
  console.log "Other team members: " +team  
  
squad = [
   "Mahendra Singh Dhoni"
   "Virat Kohli"
   "Shikhar Dhawan"
   "Rohit Sharma"   
   "Gurkeerat Singh Mann"
   "Rishi Dhawan"
   "R Ashwin"
   "Ravindra Jadeja"
   "Axar Patel"
   "Jasprit Bumrah"
   "Umesh Yadav"
   "Harbhajan Singh"
   "Ashish Nehra"
   "Hardik Pandya"
   "Suresh Raina"
   "Yuvraj Singh"
   "Ajinkya Rahane"
 ]

indian_team squad...

Abra o command prompt e compilar o arquivo .coffee conforme mostrado abaixo.

c:\> coffee -c tailing_arguments.coffee

Na compilação, ele fornece o seguinte JavaScript.

// Generated by CoffeeScript 1.10.0
(function() {
  var indian_team, squad,
    slice = [].slice;

  indian_team = function() {
    var Captain, Wicketkeeper, WiseCaptain, first, i, last, others, second, team;
    first = arguments[0], second = arguments[1], others = 4 <= arguments.length ? slice.call(arguments, 2, i = arguments.length - 1) : (i = 2, []), last = arguments[i++];
    Captain = first;
    WiseCaptain = second;
    team = others;
    Wicketkeeper = last;
    console.log("Captain: " + Captain);
    console.log("Wise captain: " + WiseCaptain);
    console.log("Wicket keeper is:" + last);
    return console.log("Other team members: " + team);
  };

  squad = ["Mahendra Singh Dhoni", "Virat Kohli", "Shikhar Dhawan", "Rohit Sharma", "Gurkeerat Singh Mann", "Rishi Dhawan", "R Ashwin", "Ravindra Jadeja", "Axar Patel", "Jasprit Bumrah", "Umesh Yadav", "Harbhajan Singh", "Ashish Nehra", "Hardik Pandya", "Suresh Raina", "Yuvraj Singh", "Ajinkya Rahane"];

  indian_team.apply(null, squad);

}).call(this);

Agora, abra o command prompt novamente e execute o arquivo CoffeeScript conforme mostrado abaixo.

c:\> coffee tailing_arguments.coffee

Ao ser executado, o arquivo CoffeeScript produz a seguinte saída.

Captain: Mahendra Singh Dhoni
Wise captain: Virat Kohli
Wicket keeper is:Ajinkya Rahane
Other team members: Shikhar Dhawan,Rohit Sharma,Gurkeerat Singh Mann,Rishi Dhawan,R Ashwin,Ravindra Jadeja,Axar Patel,Jasprit Bumrah,Umesh Yadav,Harbhajan Singh,Ashish Nehra,Hardik Pandya,Suresh Raina,Yuvraj Singh

Compreensões com Splats

Dentro da função, também podemos iterar os elementos de um splat usando compreensões, conforme mostrado no exemplo a seguir. Salve este código em um arquivo com o nomesplats_comprehensions.coffee

indian_team = (first, second, others...) ->
  Captain = first
  WiseCaptain = second
  team  = others
  console.log "Captain: " +Captain
  console.log "Wise captain: " +WiseCaptain
  console.log "Other team members:: "
  console.log member for member in others

squad = [
   "Mahendra Singh Dhoni"
   "Virat Kohli"
   "Shikhar Dhawan"
   "Rohit Sharma"   
   "Gurkeerat Singh Mann"
   "Rishi Dhawan"
   "R Ashwin"
   "Ravindra Jadeja"
   "Axar Patel"
   "Jasprit Bumrah"
   "Umesh Yadav"
   "Harbhajan Singh"
   "Ashish Nehra"
   "Hardik Pandya"
   "Suresh Raina"
   "Yuvraj Singh"
   "Ajinkya Rahane"
 ]

indian_team squad...

Abra o command prompt e compilar o arquivo .coffee conforme mostrado abaixo.

c:\> coffee -c splats_comprehensions.coffee

Na compilação, ele fornece o seguinte JavaScript.

// Generated by CoffeeScript 1.10.0
(function() {
  var indian_team, squad,
    slice = [].slice;

  indian_team = function() {
    var Captain, WiseCaptain, first, i, len, member, others, results, second, team;
    first = arguments[0], second = arguments[1], others = 3 <= arguments.length ? slice.call(arguments, 2) : [];
    Captain = first;
    WiseCaptain = second;
    team = others;
    console.log("Captain: " + Captain);
    console.log("Wise captain: " + WiseCaptain);
    console.log("Other team members:: ");
    results = [];
    for (i = 0, len = others.length; i < len; i++) {
      member = others[i];
      results.push(console.log(member));
    }
    return results;
  };

  squad = ["Mahendra Singh Dhoni", "Virat Kohli", "Shikhar Dhawan", "Rohit Sharma", "Gurkeerat Singh Mann", "Rishi Dhawan", "R Ashwin", "Ravindra Jadeja", "Axar Patel", "Jasprit Bumrah", "Umesh Yadav", "Harbhajan Singh", "Ashish Nehra", "Hardik Pandya", "Suresh Raina", "Yuvraj Singh", "Ajinkya Rahane"];

  indian_team.apply(null, squad);

}).call(this);

Agora, abra o command prompt novamente e execute o arquivo CoffeeScript conforme mostrado abaixo.

c:\> coffee splats_comprehensions.coffee

Ao ser executado, o arquivo CoffeeScript produz a seguinte saída.

Captain: Mahendra Singh Dhoni
Wise captain: Virat Kohli
Other team members::
Shikhar Dhawan
Rohit Sharma
Gurkeerat Singh Mann
Rishi Dhawan
R Ashwin
Ravindra Jadeja
Axar Patel
Jasprit Bumrah
Umesh Yadav
Harbhajan Singh
Ashish Nehra
Hardik Pandya
Suresh Raina
Yuvraj Singh
Ajinkya Rahane