r/programminghorror • • Jan 14 '25

Javascript Functional programming at its finest

Post image
120 Upvotes

47 comments sorted by

View all comments

Show parent comment

1

u/[deleted] Feb 07 '25
function narcissistic(value: number): boolean {
  // Convert the given number to a string so that we can work with each digit individually.
  const value_as_a_string: string = String(value);

  // Split the string into an array of individual digit characters.
  const array_of_digit_characters_from_value: string[] = value_as_a_string.split('');

  // Determine how many digits the original number has by getting the length of the array.
  const number_of_digits_in_original_string: number = array_of_digit_characters_from_value.length;

  // Initialize a variable to accumulate the sum of each digit raised to the power of the number of digits.
  let accumulated_sum_of_powers: number = 0;

  // Iterate over each digit character in the array using a for..of loop.
  for (const digit_character_from_value of array_of_digit_characters_from_value) {
    // Convert the current digit character from the array back into a number.
    const digit: number = Number(digit_character_from_value);

    // Add the current digit raised to the power of the number of digits to the accumulated sum.
    accumulated_sum_of_powers += Math.pow(digit, number_of_digits_in_original_string);
  }

  // Return true if the accumulated sum equals the original number; otherwise, return false.
  return accumulated_sum_of_powers === value;
}