objectMap from Array or String: The Snitch

While many of the other algonalogies have stories accompanying code… the code for this is a pretty direct expression for the analogy. Think of a “Snitch” an “Informant” from a cop movie… or in a historical light: “The Kindly Old Neighbor” who works for the Stasi or GPU (secret police), keeping track of your every social infraction. OR… in New York City, that concerned citizen who will anonymously report your car for idling.

NOTE: an objectMap (or hashMap in a language like Ruby) is a springboard for use in other algorithms. Code below:

function snitch(transgressionsWitnessed) {
  const socialScoringFile = {};
  for (let transgression of transgressionsWitnessed) {
    socialScoringFile[transgression] = socialScoringFile[transgression] + 1 || 1
  };
  return console.log("I witnessed", socialScoringFile) 
  }

The above code works like so:

snitch(["unspeak", "", "car idling", "didn't pick up after their dog"])
//returns ...

I witnessed {
  unspeak: 1,
  '': 1,
  'car idling': 1,
  "didn't pick up after their dog": 1
}

------------------------------------

snitch(("unspeak, car idling, didn't pick up after their dog, didn't pick up after their dog").split(", "))
// returns ...

I witnessed { unspeak: 1, 'car idling': 1, "didn't pick up after their dog": 2 }

------------------------------------

snitch("abcdefgABCDEfgABab")
//returns ...

I witnessed {
  a: 2,
  b: 2,
  c: 1,
  d: 1,
  e: 1,
  f: 2,
  g: 2,
  A: 2,
  B: 2,
  C: 1,
  D: 1,
  E: 1
}

With small modification, you could name your snitches… for example:

const melvinHatesCars = (carsMelvinSpiedOn) => snitch(carsMelvinSpiedOn)

console.log(melvinHatesCars(["honda accord", "toyota", "BMW", "mercedes", "mercedes", "mercedes", "mercedes", "Ford Mustang"]))

//returns 

I witnessed {
  'honda accord': 1,
  toyota: 1,
  BMW: 1,
  mercedes: 4,
  'Ford Mustang': 1
}

You could also write filters, or use looping techniques to determine the minimum, maximum, or other mathy values.

Discover more from Comedy Tragedy Epic

Subscribe now to keep reading and get access to the full archive.

Continue reading