Applied Programming/Functions/JavaScript

functions.jsEdit

/** This program converts a Fahrenheit temperature to Celsius.
 * 
 * Input: 
 *    Fahrenheit temperature
 * 
 * Output:
 *    Fahrenheit temperature
 *    Celsius temperature
 * 
 * Example:
 *    Enter Fahrenheit temperature: 100
 *    100° Fahrenheit is 37.77777777777778° Celsius
 * References:
 *    http://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html
 *    http://www.mathsisfun.com/temperature-conversion.html
 */

main();

/** main runs the main program logic. */
function main() {
  fahrenheit = getFahrenheit();
  celsius = fahrenheitToCelsius(fahrenheit);
  displayResults(fahrenheit, celsius);
}

/**
 * getFahrenheit gets Fahrenheit temperature.
 * @return {number} Fahrenheit temperature
 */
function getFahrenheit() {
  var fahrenheit = input("Enter Fahrenheit temperature:");
  return fahrenheit;
}

/**
 * fahrenheitToCelsius converts Fahrenheit temperature to Celsius.
 * @param {number} fahrenheit: Fahrenheit temperature to be converted
 * @return {number}: Celsius temperature
*/
function fahrenheitToCelsius(fahrenheit) {
  const TEMPERATURE_DIFFERENCE = 32;
  const TEMPERATURE_RATIO = 5 / 9;
  celsius = (fahrenheit - TEMPERATURE_DIFFERENCE) * TEMPERATURE_RATIO;
  return celsius;
}

/**
 * displayResults Displays Fahrenheit and Celsius temperatures.
 * @param {number} fahrenheit: Fahrenheit temperature
 * @param {number} celsius: Celsius temperature
*/
function displayResults(fahrenheit, celsius) {
  output(fahrenheit + "° Fahrenheit is " + celsius + "° Celsius");
}

/**
 * input gets input from the user based on JavaScript environment.
 * @param {string} text: text prompt
 * @result {string}: input text
*/
function input(text) {
  if (typeof window === 'object') {
    return prompt(text)
  }
  else if (typeof console === 'object') {
    const rls = require('readline-sync');
    var value = rls.question(text);
    return value;
  }
  else {
    output(text);
    var isr = new java.io.InputStreamReader(java.lang.System.in); 
    var br = new java.io.BufferedReader(isr); 
    var line = br.readLine();
    return line.trim();
  }
}

/**
 * output displays output to the user based on JavaScript environment.
 * @param {string} text: text to output
*/
function output(text) {
  if (typeof document === 'object') {
    document.write(text);
  } 
  else if (typeof console === 'object') {
    console.log(text);
  } 
  else {
    print(text);
  }
}

Try ItEdit

Copy and paste the code above into one of the following free online development environments or use your own JavaScript compiler / interpreter / IDE.

See AlsoEdit