Coding Tip: Try to Code Without If-statements

You might uncover better solutions

Code from a Facebook project. Please don’t sue them.

Challenge #1: Count the odd integers in an array

const arrayOfIntegers = [1, 4, 5, 9, 0, -1, 5];
let counter = 0;arrayOfIntegers.forEach((integer) => {
  const remainder = Math.abs(integer % 2);  if (remainder === 1) {
    counter++;
  }
});console.log(counter);
let counter = 0;arrayOfIntegers.forEach((integer) => {
  const remainder = Math.abs(integer % 2);
  counter += remainder;
});console.log(counter);

Challenge #2: The weekendOrWeekday function

const weekendOrWeekday = (inputDate) => {
  const day = inputDate.getDay();  if (day === 0 || day === 6) {
    return 'weekend';
  } 
  
  return 'weekday';  // Or, for ternary fans:
  // return (day === 0 || day === 6) ? 'weekend' : 'weekday';
};console.log(weekendOrWeekday(new Date()));
const weekendOrWeekday = (inputDate) => {
  const day = inputDate.getDay();  return weekendOrWeekday.labels[day] || 
         weekendOrWeekday.labels['default'];
};weekendOrWeekday.labels = { 
  0: 'weekend', 
  6: 'weekend', 
  default: 'weekday' 
};console.log(weekendOrWeekday(new Date()));

Challenge #3: The doubler function (here be dragons)

const doubler = (input) => {
  switch (typeof input) {
    case 'number':
      return input + input;
    case 'string':
      return input
        .split('')
        .map((letter) => letter + letter)
        .join('');
    case 'object':
      Object.keys(input)
            .map((key) => (input[key] = doubler(input[key])));
      return input;
    case 'function':
      input();
      input();
  }
};console.log(doubler(-10));
console.log(doubler('hey'));
console.log(doubler([5, 'hello']));
console.log(doubler({ a: 5, b: 'hello' }));
console.log(
  doubler(function() {
    console.log('call-me');
  }),
);
const doubler = (input) => {
  return doubler.operationsByType[typeof input](input);
};doubler.operationsByType = {
  number: (input) => input + input,
  string: (input) =>
    input
      .split('')
      .map((letter) => letter + letter)
      .join(''),
  function: (input) => {
    input();
    input();
  },
  object: (input) => {
    Object.keys(input)
          .map((key) => (input[key] = doubler(input[key])));
    return input;
  },
};console.log(doubler(-10));
console.log(doubler('hey'));
console.log(doubler([5, 'hello']));
console.log(doubler({ a: 5, b: 'hello' }));
console.log(
  doubler(function() {
    console.log('call-me');
  }),
);

samerbuna.com

jsComplete EdgeCoders

We write about the new and leading edge technologies with a focus on JavaScript

Samer Buna

Written by

Author for Pluralsight, O'Reilly, Manning, and LinkedIn Learning. Curator of jsComplete.com

jsComplete EdgeCoders

We write about the new and leading edge technologies with a focus on JavaScript