Categories
Uncategorized

Two Arrays: Don’t Double Loop

I ran into a coding challenge at work. I had to arrays of objects. I needed to get the _id from artists and add it to artworks array. I did this whole dance in running two nested loops to get what I needed. Here’s a sample of the input and expected output:

const artits = [
	{
		"byline": "Clay Smith",
		"_id": "SmithC",
	},
	{
		"byline": "Rick Slick",
		"_id": "slick_rick",
	},
	{
		"byline": "Tracy Tran",
		"_id": "ttran",
	}
]

const artworks = [
	{
	  "id": "CBE220126c.jpg",
	  "name": "Clay Smith",
	},
	{
	  "id": "RS220236c.jpg",
	  "name": "Rick Slick",
	},
	{
	  "id": "TT220216c.jpg",
	  "name": "Tracy Tran",
	}
]

// output
const expectedOutput = [
	{
	  "id": "CBE220126c.jpg",
	  "name": "Clay Smith",
	  "_id": "SmithC",
	},
	{
	  "id": "RS220236c.jpg",
	  "name": "Rick Slick",
	  "_id": "slick_rick",
	},
	{
	  "id": "TT220216c.jpg",
	  "name": "Tracy Tran",
	  "_id": "ttran"
	}
]

Okay lets take a look my first attempt, with ugly nested loops.

let output = []
// O(n)^2
const artistsAndArtworks = artists.forEach((artist) => {
	artworks.forEach((artwork) => {
		if (artist.byline === artwork.name) {
			output.push({
				...artwork,
				_id: artist._id
			})
		}
		
	})
});
// console.log(output);

Why is this ugly? Well, I am iterating through one collection and then another inside of it. What that means is in a worse case scenario, such as having lots and lots of records, I have to take the first trip from start to finish for the first track, and also run through the second track start to finish (with presumably lots of records), one by one per collection. That can take up a lot time!

Our big O is n^2. That’s an exponential graph there. We have an expensive solution regarding time.

So why is this a solution though? First off, the arrays presents as two lists. Why that is meaningful is because lists mean you can loop through them with our trusty array methods!

If I was doing this manually, I imagine myself going searching for the artist byline and matching against the artwork’s name. If I find a match, then build an object with a copy (spread) of the current artwork, and add the _id from the current artist. Kind of shitty, but it works.

This is how I usually think and I know it’s not optimal. It can be better. So how can we avoid nesting loops but get the look up we want for an _id ? My pal, Freddy Montano, helped me think about the problem from a different perspective. A great way to look at this is map the name of the artist to an _id. The best thing about maps is that you can access content much easier than looping through.

There is a name in the artworks, that name can serve as a relation key. Following me? A relation key as in a key to a value object. An object! Aint finding stuff in objects pretty easy? It is.

const artistMap = artists.reduce( (acc,artist) => {
	acc[artist.byline] = artist._id
	return acc;
}, {});

const artworkMap = artworks.map(artwork => {
	return {
		...artwork,
		_id: artistMap[artwork.name]
	}
});
console.log(artworkMap);

Isn’t that more elegant? So lets take a look at the reduce() method there. I personally am still surprise in finding how powerful this method is. I sort of think a reduce() is like running a tab with a waiter. That waiter is keeping track of what you’ve been ordering in your group. The waiter in the reduce() is our accumulator.

First lets initialize our reduce() with an empty object, {}. We want to create an object to quickly look up our _id for a given artist.

...}, {});

Let’s look at the inside of the method. The real magic is in this line:

acc[artist.byline] = artist._id

By assigning our acc to a computed property, or calculated key, to the the artist id, you get an output like this:

{ "Tracy Tran": "ttran"}

Pretty neat! Now we got an object that maps from the artist name to their _id. Our returned object is assigned to artistMap.

Now we can simply loop through our collection of artwork and add our _id. But first two mental steps to achieve.

  1. We want to copy everything in the array’s current object
  2. Append to that object the _id. How do we look up the _id?

We can copy our object by using a spread method:

...artwork

Pretty easy! Next is a little tricky. The name is the key in artistMap object. My first thought was to do artists[something goes here. That will fail! It will fail because artists is an array and that’s not how you look up (unless you know the index). Instead I attempted to do artwork[ something goes here ]. That certainly does not make sense because artwork does not contain our _id yet.

Remember, our artistMap is an object. We can use that to look up with artwork.name to match for the byline of the artist.

_id: artistMap[artwork.name]

Seems obvious! But a good perspective to keep is the beginner’s mind. The steps to get there reveals the path. The destination is pretty clear once you get to where you are going.

Lets visualize whats going on with the _id assignment

_id: artistMap['Clay Smith'] will search for Clay Smith in our object (note that object keys are always unique).

{"Clay Smith": 'SmithC'}

The result will be _id: "SmithC". We avoid two nested loops and leverage a data structure, our little object to gain better performance. The trade off is taking up some memory for looping our collection and adding a new object.

This was fun ride. Thanks for reading.

Media Diet for Late 2021

Dune (2021). I watched the film last night and I am blown away. I lessen my expectations going into it. But that was needless. It’s an excellent film. 😄

Dune (book). I am only 25% into it. So far its holding my attention.

Mr.Robot seasons 1 to 3. Watching this after the election 2020, its eerily prescient regarding cyber warfare, malicious foreign hackers, ransomware, movement groups getting over their heads, and scarily referencing 5/9 (Jan 6 for us) as a date of importance. This is show could of have been a shallow conspiracy driven drama, but it very much develop a parallel world. I couldn’t watch this show because it was a little too close to the real world. 😄

Destiny Disrupted by Tamim Ansary. When I was a high school I did an essay on China and why it wasn’t a superpower in the 20th Century. China on the surface look to have had a head start on technology, governance, commerce, and economic growth. But for many different complicated reasons, it didn’t turn out that way. The essay helped me learn seeing the world history through the lens of China’s history. This book is about Islam and looking through the world through the lens of Islam’s history. One interesting historical thing was Omar, the second Caliphate [sic], ruled over an empire in the same stature as Alexandria the Great. This was totally not mentioned in my high school world history text book.

Cyberpunk 2077. Like Mr. Robot, I’ve put off playing this game because of the casual cruelty the game portrays in it’s story. I’ve discovered the mage class is the net runner build. Once I realized the net runner build is a magic casting hacker, I was sold. Cyberpunk is fun! ※\(^o^)/※

Retropie. I’ve rebuilt my retro gaming console. I had to flash the SD card and install Retropie onto it. The problem was that the hardware was not saving any settings or games after reset or shutting off. Playing some of my old games I’ve owned since I was a kid is a joy.

NZXT b550 and Ryzen 5600x. I’ve upgraded my PC. I accidentally fried my motherboard and I had to get a replacement. In doing so, I’ve upgrade my PSU to a Corsair 750w and my RAM to Corsair Vengeance 36000 16gb with RGB. I really like my setup now. Games load up way quicker. Streaming to my steam link is way faster and better. I’ve learned a lot in putting together a PC. Its kind of fun despite things not working a lot of times. I often feel some validation that my bet that PC gaming is more affordable (steam sales) and better experience (better hardware) has come into fruition. There are rare exclusive on PS5 or Xbox, but I think I can wait when those exclusives come to PC, e.g. Horizon Dawn Zero or maybe Final Fantasy VII Remake.

 

IMG 2444

Here’s the old PC without the case. You can see my retro game controllers there too.

IMG 2457

 

Keychron Q1, brown switches. I really love typing on this new mechanical keyboard. It is fabulous in it’s sound and thunk. The RGB is very pleasant. I got Sara to get the k6 for herself. 

⌨️

IMG 2359

Categories
Uncategorized

Jon Stewart has something to say

New York Times Magazine interviewed Jon Stewart for his new show, “Irresistible”. The whole thing is quotable. I kept finding myself highlighting and underlining what he was saying. Here’s a few.

Systems capture all who are part of it, even if they can’t see it:

Don’t people know that already? The politicians don’t even know how expletive1 up their system is. Nancy Pelosi2 was on ‘‘The Daily Show,’’ and we were talking about how money has a corrupting influence in politics. I said, ‘‘You raised $30 million. How does that money corrupt you?’’ She said it doesn’t. So money corrupts, but not you? That’s someone within the system.

The two party system as a duopoly:

In June 2019, Stewart spoke before Congress in support of a bill authorizing increased funding of medical coverage for 9/11 first responders. The bill passed in July of the same year.

I learned something that shocked me. We had a program that was working. Bureaucratically, it wasn’t broken. What is broken about Washington isn’t the bureaucracy. It’s legislators’ ability to address the issues inherent in any society — and the reason they can’t address them is that when you have a duopoly, there is no incentive to work together to create something better.

He’s not wrong about the two party system as a duopoly. From Stewart’s standpoint, the two political parities have little reason to work together. If compromise means weakness to the other side, then it’s really important to not give an inch on such and such bill. On social media and Sunday morning talk shows, someone has to eviscerate or dominate or destroy the other side.

But it’s my opinion, that the dysfunctional system is not necessarily rooted in the duopoly of the two political parties, and thereby lack of competition of political parties.

In Ezra Klein’s book, Why We Are Polarized, Klein makes a case that the dysfunctional system has many deeply complicated reasons. One of which is that one political party is captured by the forces of polarization, and has very little immune response to radicalization and self-sabtaoge. They must feed anger and rage to their base.

In 2012, the two scholars published It’s Even Worse Than It Looks, and in it, they minced no words: Today’s Republican Party … is an insurgent outlier. It has become ideologically extreme; contemptuous of the inherited social and economic policy regime; scornful of compromise … Between 2012 and 2018, House Republicans drove John Boehner from the speakership for being insufficiently radical and then made Paul Ryan’s life so miserable he resigned the post after only three years. … Republicans repeatedly shut down the federal government.

[And Donald Trump shutdown the government with his party in power for not getting funding for his border wall]

In all these cases, top Republicans expressed unease with the path they had chosen but seemed helpless to do anything but channel the fury of their base.

Why We Are Polarized – loc 3366

The Democrats cannot afford to abandon the center and simply feed the base alone. Instead they have to appeal to a large range of people.

It [elections] means winning liberal whites in New Hampshire and traditionalist blacks in South Carolina. It means talking to Irish Catholics in Boston and the karmically curious in California. Democrats need to go broad to win over their party and, as we’ll see, they need to reach into right-leaning territory to win power.

Why We Are Polarized – loc 3438

Senator Manchin of West Virgina and AOC are in the same party, but they have very different things to say about the climate change. House Speaker Pelosi and Minority Leader Schumer, having to keep this diverse coalition together, must make appeals from the center to the Left.

Stewart has a good point on the duopoly, though. I, like Ezra Klein, see it through the lens of polarization and identity politics. I’d would include as well, the inability for the two political parties to work together is the result of not only deepening polarization, but also escalating constitutional hard-ball, and disappearing forbearance to the minority political party, To read more about this, look to How Democracies Die.

Stewart continues with the idea that one party is set out to sabotage the very thing they represent:

Plus, you have one party whose premise is that government is bad and whose goal is to prove that, which makes them, in essence, a double agent. All these things coalesce to make problem-solving the antithesis of what we’ve created. We’re incentivized for more extreme candidates, for more extreme partisanship, for more conflict and permanent campaigning, for corporate interests to have more influence on the process, not less. The tax code isn’t complicated because poor people have demanded that it be that way.

On where the burden of this nation’s ideals should be.

There’s always this begrudging sense that black people are being granted something, when it’s white people’s lack of being able to live up to the defining words of the birth of the country that is the problem.

  1. I believe, the word is “fucked”
  2. NY Times footnote: A guest on ‘‘The Daily Show’’ in 2014 while she was House minority leader. The back-and-forth that Stewart describes here is his paraphrasing of the conversation. In retrospect, the interview looks like a preview of the themes of ‘‘Irresistible.’’
Categories
Uncategorized

Media Diet June 2020

Thirteen depicts the evolution of the system around the criminalization of African Americans from post Civil War to today. The 13th Amendment freed enslaved people, but with one critical loophole, though, the amendment excluded criminals. The South, in ruin from the Civil War, sought to rebuild their economy with equal mistreatment and cost of labor. So by enforcing petty crimes, they rounded up many and many newly freed Black people, and put chains back on to them. Today, through mass incarceration, many corporations use imprison labor to make products, that you and I use everyday.

It’s deeply heartbreaking to see how ruthlessly efficient our country has eaten up communities. Chris Hayes in his book, A Colony in a Nation, argues this point that we are nation that has two systems: one for the nation that applies democratic principles of justice such as presumption of innocence; another for the colony, to control a population with lethal and brutal force.

One silver lining is seeing that BLM does not depend on a leader to push for change. The movement has seen a 25+ point increase in support. Changes in police departments are happening in several cities. And Minneapolis is dismantling their police entirely. (A)

Carley Rae Jepson dropped her b-side to Dedicated. First song, This Love Isn’t Crazy is a real banger. I imagine having a lot fun dancing to this at a club or dance hall. Overall the album is pretty good. (B+)

Taylor Swift’s Lover is pretty darn good. Favorites are Death by Thousand Cuts, Man, I Forgot You Existed, It’s Nice to Have a Friend. Perhaps it’s the album where Taylor Swift decided to speak out against the Donald Trump that has me enjoying it a little more. (A)

Kipo is a wild anime. It’s has hip hop and rap as underlying music. And the characters are all compelling. It depicts an America 200 years after the collapse of society. People live underground and animals have mutated to be sentient. The combination of different animals and their tribe’s culture is really interesting. (A-)