AM|FM

Filter and Total Only Even Numbers in JS and C#


    I'm not a fan of the coding interview and do not think it is a good measure of the experience and creativity of a developer. Why memorize something that can easily be looked up, einstein?
Recently when applying for a job, the recruiter gave me a sample coding question a prior candidate flunked. Poor guy/gal, the code looked decent to me especially considering that this is something this poor soul had to pull out of thin air from their grey-matter while being watched by the interviewer. The core concepts of their solution were on point to me, but this person was rejected as the code was


"not what they were looking for..." ¯\(ツ)


What were they looking for? The syntax was of the classic for (i =0; i <= 100; i++). Were they looking for some of that sweet syntactic sugar? Did the candidate have halitosis? Maybe the hiring manager had already chosen someone? Your guess is as good as mind.

So, I wanted to try this exercise and hammer out this question in the JS and C# styles I like -- using arrow functions and LINQ queries. The question is:
Given an array of ints, write a method to total all the values that are even numbers.


    

  1. First, for data, we initialize a numbers array.
  2. Define our function, using arrow functions. It will receive the numbers array as a parameter.
  3. Inside the function, we create a local variable totalEven to hold our result.
  4. We call the .filter array method on the numbers array. I ❤ filter and like my relatives in the antique business, he's a picker. He'll pick through an array, a list, a table, a dusty old storage unit -- whatever -- until he finds something of value. Filter is going to pick elements within the array that meet some condition/criteria.
  5. Our condition/criteria is if item % 2 === 0. What does this mean, modulus freaks me out man!? It used to freak me out too brother until I sat down in the chill down tent and looked into the basic maths involved here. Modulus returns the remainder if there is one. Here we are checking to see if the number is divisible by two ( % 2 ) and then verify that there is no remainder left ( === 0 ). For instance, when 5 is evaluated during the iteration, 5 divided by 2 leaves a remainder of 1 which is not equal to 0. (1 === 0). Off to the ether with you. You are a bad apple and the picker is throwing you out. You are old silverware that no descendent wants to shine. But, if we divide 4 by 2, we get no remainder, so it is true that 0 === 0. The picker picks you. A real keeper, you're as valuable and popular as fiestaware.

TANGENT : Basically, this type of operation is common. I've seen it used like in classic fizzbuzz. If some when asks you a question regarding even and odd numbers and to carryout some process based on their even-ness or odd-ness, think x % 2 === 0. That algorithm was probably painted on a cave wall somewhere many a millennia ago.


  1. Next, now that the picker has its pick (via filter), we need to sum the total. We need to sum all of our picks together and we'll use the reduce() function for this. Its syntax is confusing, but basically is .reduce((accumulator, current)) => <SOME_LOGIC_FOR_ACCUMULATOR_AND_CURRENT_OR_CALLBACK_FUNCTION>, <INITIAL_VALUE> Sorry that was long winded but that is how I see it. acc, the accumulator, I like to think in my folksy way, we could just call it the tally. Some people call it "previousValue". You could call it Susan -- anything. Our logic here runs up the tally, adding the current pick to the tally. So 2 is picked, stored, then 4 is picked and added to the running tally, 2 + 4 = 6.
  2. Finally we invoke the function, passing in our numbers array the sum is logged :
    Sum of even numbers: 6

JAVASCRIPT

                        //DATA
			const numbers = [1, 5, 2, 7, 4];

			//DEF
			const getSumEvenNumbers = (numbers) => {
			    
			    const totalEven = numbers.filter(item => item % 2 === 0)
			                             .reduce((acc, curr) => acc + curr, 0); 
			    
			    console.log(`Sum of even numbers: ${totalEven}`);
			};

			// INV
			getSumEvenNumbers(numbers)

			// OUT
			// Sum of even numbers: 6


  1. For the C# version, we create a strongly-typed array of ints (int[]) and go ahead and initialize it with the curly braces.
  2. We'll create a static void method for our GetSumEvenNumbers() that receives only number arrays int[] as arguments.
  3. We create a local variable typed as int because we are outputting a single value which will hold the result of our picking and totaling logic -- int totalEven.
  4. Inside the method, we use LINQ's .Where() function. I like it because it is as easy breezy like JS's .filter. Compare how remarkably similar they are. If you want to memorize both C# / JS versions, go with arrow functions and LINQ, for the sake of their similarity. JS arrow functions and C# LINQ are brothers from another mother in my opinion. The logic is the same, we iterate through the array and PICK the elements which are divisible by two and leave no remainder(0).
  5. We then have a convenient, simple .Sum() function that will tally them all together, a lot more succinct than that barbarous .reduce() function we saw prior.
  6. Once again, The function is invoked in Main(), and the result is printed to the console.

CSHARP


                        using System;
			using System.Linq;

			public class Program
				{
				public static void Main()
				{	
					//DATA
					int[] numbers = { 1, 5, 2, 7, 4};
					    
				    //INV
    				// p1 : numbers array of ints, int[]
    					GetSumEvenNumbers(numbers);
				} 

			    
			    public static void GetSumEvenNumbers(int[] numbersCalc) {
			        int totalEven = numbersCalc.Where(item => item % 2 == 0).Sum(); 
			        Console.WriteLine($"Sum of even numbers : {totalEven}");
			    }

				} //end program

Final Notes -- Improvements here? DO USE TYPESCRIPT.

  1. Type the numbers array as an array of numbers -- number[].
  2. Type totalEven as number, since it holds a single numeric value.
  3. Since the function doesn’t return a value, type it as void.

Here is the typescript version:


TYPESCRIPT

                              // DATA
				const numbers: number[] = [1, 5, 2, 7, 4];

				// DEF
				const getSumEvenNumbers = (numbers: number[]): void => {
				    
				    const totalEven: number = numbers
				        .filter((item: number) => item % 2 === 0)
				        .reduce((acc: number, curr: number) => acc + curr, 0);
				    
				    console.log(`Sum of even numbers: ${totalEven}`);
				};

				// INV
				getSumEvenNumbers(numbers);

				// OUT
				// Sum of even numbers: 6



Questions? Comments? Corrections? I am human all too human but please feel free to contact me at csdear138@gmail.com