Condividi tramite


Funzioni JScript definite dall'utente

Per quanto in JScript siano disponibili numerose funzioni predefinite, è comunque possibile crearne di personalizzate. Una definizione di funzione è costituita da un'istruzione di funzione e da un blocco di istruzioni JScript.

Definizione di una funzione personalizzata

Nell'esempio che segue, la funzione checkTriplet ha come argomenti le lunghezze dei lati di un triangolo. Questa funzione calcola se il triangolo è quello corretto verificando se i tre numeri costituiscono una terna pitagorica, ossia convalidano la regola secondo cui in un triangolo rettangolo, il quadrato della lunghezza dell'ipotenusa è uguale alla somma dei quadrati delle lunghezze degli altri due lati. Per l'effettiva esecuzione del test, la funzione checkTriplet richiama un'altra funzione.

Si noti l'utilizzo di un numero molto piccolo (epsilon) come variabile di test nella versione a virgola mobile del test. Considerate le incertezze e gli errori di arrotondamento nei calcoli a virgola mobile, è preferibile non verificare direttamente se i tre numeri costituiscono una terna pitagorica a meno che non sia noto che tutti e tre i valori sono valori integer. Poiché un test diretto è più preciso, mediante il codice illustrato nell'esempio si stabilisce se il test è appropriato e, in caso positivo, lo si utilizza.

L'annotazione del tipo non viene utilizzata nella definizione di queste funzioni. In questa applicazione è utile che la funzione checkTriplet accetti sia tipi di dati integer che tipi di dati a virgola mobile.

const epsilon = 0.00000000001; // Some very small number to test against.

// Type annotate the function parameters and return type.
function integerCheck(a : int, b : int, c : int) : boolean {
   // The test function for integers.
   // Return true if a Pythagorean triplet.
   return ( ((a*a) + (b*b)) == (c*c) );
} // End of the integer checking function.

function floatCheck(a : double, b : double, c : double) : boolean {
   // The test function for floating-point numbers.
   // delta should be zero for a Pythagorean triplet.
   var delta = Math.abs( ((a*a) + (b*b) - (c*c)) * 100 / (c*c));
   // Return true if a Pythagorean triplet (if delta is small enough).
   return (delta < epsilon);
} // End of the floating-poing check function.

// Type annotation is not used for parameters here. This allows 
// the function to accept both integer and floating-point values 
// without coercing either type.
function checkTriplet(a, b, c) : boolean { 
   // The main triplet checker function.
   // First, move the longest side to position c.
   var d = 0; // Create a temporary variable for swapping values
   if (b > c) { // Swap b and c.
      d = c;
      c = b;
      b = d;
   }
   if (a > c) { // Swap a and c.
      d = c;
      c = a;
      a = d;
   }

   // Test all 3 values. Are they integers?
   if ((int(a) == a) && (int(b) == b) && (int(c) == c)) { // If so, use the precise check.
      return integerCheck(a, b, c); 
   } else { // If not, get as close as is reasonably possible.
      return floatCheck(a, b, c); 
   }
} // End of the triplet check function.

// Test the function with several triplets and print the results.
// Call with a Pythagorean triplet of integers.
print(checkTriplet(3,4,5));
// Call with a Pythagorean triplet of floating-point numbers.
print(checkTriplet(5.0,Math.sqrt(50.0),5.0));
// Call with three integers that do not form a Pythagorean triplet.
print(checkTriplet(5,5,5));

L'output del programma è il seguente:

true
true
false

Vedere anche

Riferimenti

Istruzione function

Altre risorse

Funzioni JScript

Tipi di dati JScript