How to prevent jQuery from loading image in parseHTML

This post is inspired by a recent bug fix at work related to jQuery’s parseHTML() method.

I noticed multiple redundant calls to our server endpoint each time a user saves an email template using the drag-and-drop email builder of Metisa.

The bug, when traced to its end, was nothing like what I’d originally suspected. Because we use Backbone.js for the front-end model layer (to make API calls) with React.js as the front-end view layer, I had initially thought it was Backbone making redundant API calls.

But with about an hour of digging, I found out that calling $.parseHTML('<img src="path/to/image.png">') was at fault. parseHTML() turns the string '<img>' into a DOM node, and that was immediately making GET requests for the image resource – even before appending the DOM node into the actual document!

To be sure, this is not a bug in the jQuery library. Apparently it’s expected behaviour.

Anyhow, I didn’t need 3 calls for 3 placeholder images for a DOM node that would never be appended to the actual document. It was just unnecessary load on our server. So I needed a solution.

The solution I found to work was creating a new document and passing that as the context into parseHTML(). It works like this:

This solves the problem by telling jQuery explicitly that it should parse the string in a separate context from the current document context (ie. away from the window that the user is browsing). A quick look at the jQuery documentation for the method shows that the second parameter is meant exactly for this:

Use case for parsing HTML outside of current document

I stumbled upon this obscure problem when I was developing a drag and drop email builder at work.

Each time a user in the email builder interface hits “Save,” we use jQuery to generate a string that is representative of the HTML needed for rendering in an actual email (email HTML looks horrendous, by the way, with tables nested inside tables… full rant here).

We use jQuery’s parseHTML method as a nice way to validate that a string is valid HTML (and strip off the potential security vulnerabilities) before saving it to the backend.

So what other use cases might there be for calling parseHTML in a separate document context? I don’t know exactly, but I imagine there are other situations where knowing this little trick might be helpful.

Let me know in the comments section if you’re using this technique to circumvent the default loading of image resources (or any resources for the matter)! I’d love to learn other situations where this might be helpful.

For more posts like this, check out Bite Size Programming. If you want to get the most interesting posts from this blog, subscribe and I’ll send you a weekly curated list straight to your inbox. It’s free. See you soon!

What is DRY (in programming)?

what is dry blog banner nickang showing weed growing on white wall
Photo by Ben Neale on Unsplash

Ever heard someone tell you that your code is not “DRY”? What’s the deal with that? Are they saying that your code can hold a lot of water…?

Sorry for the bad joke. DRY is an acronym, and it stands for Do not Repeat Yourself. As far as I can tell so far in my short career as a software engineer, this is one of the most revered principles in writing software.

In this post, we’ll explore why it’s important to keep your code DRY and in general, how you can go about doing it.

Continue reading “What is DRY (in programming)?”

Why use Binary Search Tree?

why use binary search tree banner with peace hand sign
Photo by Nathan Fertig on Unsplash

If you already know what a binary search tree is for and how it works, read on to learn about their main strengths and weaknesses in this post! Otherwise, feel free to take a moment to read part 1 for an introduction.

Why is a binary search tree useful? What are some of its main weaknesses?

Let’s try and answer those questions in this post.

Continue reading “Why use Binary Search Tree?”

Binary Search Tree explained

binary search tree explained nickang blog banner
Not my arm. Photo by Patrick Fore on Unsplash

What is a binary search tree? How is it related to binary search? Is it an algorithm or a data structure?

In this post I’ll share what I’ve learned about binary search tree in the last week from videos, tutorials, and practice. As usual, the resources I used to learn about this data structure (you caught your first lesson already!) will be shared at the bottom of this post.

Without any further delay, let’s dive in!

What is a binary search tree?

A binary search tree is a data structure. That means it stores data in its own unique structure.

In a binary search tree, each data element (or data item, or data point… call it what you want) is stored in a node within a tree structure, and each node in the tree can have a maximum of 2 children nodes attached to it – one on the left, another on the right.

Here’s an illustration:

binary search tree illustration
My best rendition of a Binary search tree

Each circle is a node in the overall binary search tree. As you can see, not all nodes have a parent (eg. the root node at the top) and not all nodes have children nodes (eg. every extreme last node).

How this structure is useful will become apparent in a bit. For now, let’s try and understand how a new data element is added to an existing binary search tree, which should allude to the usefulness of this structure.

Ok, so how do the nodes get placed?

Let’s say we have a new value to store in an existing binary search tree with a few nodes already. Every new piece of data is stored in a node, so we’ll need to place a new node on the tree.

Nodes are placed in the same way binary search is carried out. That is, we start at the first node at the top and ask: is the new value (and therefore new node) that I’m trying to add smaller or bigger than the current node’s value?

As a rule, if the new value is smaller than or equals to the current node’s value, we attempt to create a new node to its left. If it’s a bigger value, we attempt to do the same but on the right.

binary search tree add new node
Smaller or equal values go left, and bigger values go right

Notice I said attempt. That’s because each time we move to inspect a node, we’d have to check if it already has a child in the position we want to create a node at.

If it already exists, we basically repeat what we did in the previous node – ask “is the new data element’s value smaller or bigger than the current node’s value?” and move to the left or right again.

Here are the rules laid out in bullet points:

  • Every node can only have 0, 1, or 2 children nodes
  • Children nodes can be added to an existing node either on the left or right position
  • If a new data element’s value is smaller or equal than the current node, we check if the current node has a left child – if not, we create a new node and place our new data element there
  • If a new data element’s value is bigger than the current node, we check if the current node has a right child – if not, we create a new node and place our new data element there
  • Or else if a child node exists in the position we checked, we repeat the previous 2 steps until we find a node with no left or right child, and create a new node there with the data element

So that’s how a new data element is added to a binary search tree.

Now on to a small technical qualifier – what I’ve just said it is not completely accurate. Each “node” would actually be more accurately seen as a separate binary search tree in itself.

binary search tree nodes
Each “node” in a binary search tree is actually another binary search tree

So each “node” is a binary search tree that is contained in another binary search tree. Also, in terms of implementation, each “node” is created from the same BinarySearchTree constructor function as the original binary search tree object.

It’s not a big deal in my opinion, but it’s a good to know.

If you’ve read this far, you now know how a binary search tree is structured! But you may be asking, why is it called a binary search tree?

How is binary search tree related to binary search?

The quick answer is this: a binary search tree implements a data structure that is based on the binary search algorithm. That’s why it takes its name.

Firstly, in case you don’t already know what binary search is, you can read about it in my post on that.

As a short refresher, binary search is a remarkably efficient search algorithm that halves an input array with each iteration, keeping only the half that it knows contains the item we’re searching for. It continues until it finds the item we’re looking for and returns it.

Binary search (the algorithm, not the tree data structure) can do this “keep half, discard the other” implicitly because the input array is expected to be sorted (eg. by names in a phonebook). If it’s not sorted, the algorithm will not work correctly.

So how is this similar to a binary search tree (BST)?

In terms of searching a binary search tree, the process is actually identical.

Imagine that you’re searching our binary search tree for a particular value, say, 8. How might you do it?

Try it with the tree you saw earlier. Literally, search for the value 8, step by step, asking the golden question “is it smaller or equals to the value or bigger?” and go left and right until you find the value. Go on, I’ll wait!

Ok, so here’s how we might search a value in a BST:

  1. Start from the parent-most BST at the top
  2. Check the value of that BST: is the value I’m searching for less or equals to or more than the current BST?
  3. (Less than or equals to) Keep searching the left side of the current BST, discard the entire right side of the current BST, and examine the new BST
  4. (More than) Keep the right side of the current BST, discard the left side of the current BST, and examine the new BST
  5. Repeat until you find the value or hit the last BST with no children BSTs, and return the binary search tree or null-ish value

This is exactly like binary search, where we half an input list to get the entry in the mid-point, check if it’s the value we’re looking for and if not, discard one half and repeat the same step on the remaining half until we find the value (or find none).

In other words, a BST is a data structure that maintains a perpetually sorted tree (each time a new value is added, it is always added at the “right” place that enables quick binary search).

Wrap up

  • A binary search tree (BST) is a data structure
  • Each “node” in a BST is actually another BST with 0, 1, or 2 children nodes, and they have the same methods available to them as any BST
  • Conceptually, it’s usually easier to just refer to each point in a BST as a “node”
  • Addition of a new node is based on its value in relation to the nodes in the tree, and follows a specific rule (smaller or equal values go left, and bigger values go right)
  • The way search is carried out on a BST is identical to the binary search algorithm

And there you have it – the binary search tree explained! Hope you learned something from this post.

In the next post I discuss some of the strengths and weaknesses of a binary search tree.

For more posts like this, check out Bite Size Programming. If you want to get the most interesting posts from this blog, subscribe and I’ll send you a weekly curated list straight to your inbox. It’s free. See you soon!

Binary Search explained

binary search blog banner nickang
Photo by Pablo Garcia Saldaña on Unsplash

If you’re a software engineer, you’ve probably heard about binary search before. And if you don’t know what it is, how it’s implemented, and its strengths and weaknesses, this post is for you.

Binary search is, as its name suggests, a search algorithm. In fact, it’s one of the most efficient and commonly used search algorithms.

Continue reading “Binary Search explained”

How to implement a Linked List in JavaScript

implement linked list in javascript banner nickang
Photo by LinkedIn Sales Navigator on Unsplash

In this post, you’ll learn how to implement a linked list in JavaScript. This is the second part of a 2-parter post on linked lists (read part 1).

Let’s jump right in!

Continue reading “How to implement a Linked List in JavaScript”

Linked List explained

linked list explained banner nickang
Photo by Simon Abrams on Unsplash

A linked list is one of many commonly used data structures. The first thing to know about linked lists is that they are not the same thing as array-like primitives (eg. Array in JavaScript or List in Python). They are similar in some ways, but they have different strengths and weaknesses.

In this post, we’ll explore what a linked list is, why there’s a need for it in certain situations, and its general strengths and weaknesses, especially in relation to primitive arrays that you’re probably already familiar with.

Continue reading “Linked List explained”

Algorithm time complexity and the Big O notation

bite size programming algorithm time complexity and big o notation banner
Photo by Lysander Yuen on Unsplash

Big O notation has attained superstar status among the other concepts of math because of programmers like to use it in discussions about algorithms (and for good reason). It’s a quick way to talk about algorithm time complexity.

While it’s a math concept that applies to various fields, programmers are probably one of the most frequent users of Big O. We use it as a shorthand to discuss how quickly and/or with how much memory an algorithm takes to go from start to finish.

Perhaps the part about Big O being most used by programmers is just my carpal-tunnel-visioned mind speaking, but nevertheless! It’s an important concept and here’s a post dedicated to understanding the Big O notation.

Continue reading “Algorithm time complexity and the Big O notation”