JavaScript DeepClone function created by ChatGPT and it works

One thing I hate dealing with is cloning JavaScript Objects. Well, deep cloning JavaScript Objects. So I decided to see if AI could write me a quick function.

And it did.

I asked ChatGPT “Can you write me a JavaScript function which will deep clone a JavaScript Object?”

And this was it’s response:

Certainly! You can create a deep clone function in JavaScript using recursion to clone nested objects and arrays. Here’s a sample function to deep clone a JavaScript object:

function deepClone(obj) {
  if (obj === null || typeof obj !== 'object') {
    return obj;
  }

  if (Array.isArray(obj)) {
    const cloneArr = [];
    for (let i = 0; i < obj.length; i++) {
      cloneArr[i] = deepClone(obj[i]);
    }
    return cloneArr;
  }

  const cloneObj = {};
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      cloneObj[key] = deepClone(obj[key]);
    }
  }

  return cloneObj;
}

You can use this deepClone function to create a deep copy of a JavaScript object. Here’s an example of how to use it:

const originalObj = {
  name: 'John',
  age: 30,
  address: {
    street: '123 Main St',
    city: 'Exampleville',
  },
};

const clonedObj = deepClone(originalObj);

console.log(clonedObj);

The clonedObj will be a deep copy of the originalObj, so you can modify it without affecting the original object.

Add a mime-type to an ASP.NET Core (.NET 6) app

If you have a .NET 6 app with static files and you put in a file with a non-web standard extension somewhere in your WWWROOT you will possibly get a 404 if you try to access the file. This is because the app.UseStaticFiles(); option you add to your Program.CS file has a predefined list of files it will deliver from your site. For security reasons, anything not on this list gets blocked.

But the good news is, you can tell the app to add your file type to the Green Lit list. You just need to add a CotentTypeProvider to the StaticFileOptions passed to your UseStaticFiles method. In the code sample below, I am adding a proprietary .JSON file format with the extension of .RDLX-JSON which is blocked by default.

You still need to make a second, empty call for app.UseStaticFiles(); to have it serve the default filetypes.

var provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();

provider.Mappings.Add(new KeyValuePair<string, string>(".rdlx-json", "application/json"));

app.UseStaticFiles(new StaticFileOptions()
{
    ContentTypeProvider = provider
});

app.UseStaticFiles();

Now, when you rebuild your app, your file should be accessed via a URL like other web files.

VS Code: Sort lines of code in Ascending (or Descending) Order

Select the code you wish to sort in Visual Studio Code.

Then hit the key combination Ctrl+P and type the greater than sign (>). Next type sort and choose Sort Lines Ascending or choose the Descending option.

Now the lines you’ve previously selected will be sorted by the option you chose. One thing to keep in mind is that if you have lines which have breaks in them, the second line will also be sorted into the mix. Which may mess up formatting for things like CSS Property values.

How to pad a string in JavaScript

Sometimes you need your string to be a set length, like maybe you have numbers that all need to be 10 characters long regardless of the number value. Or maybe you have a credit card number and want to just show the last 4 digits while everything else is replaced with an asterisk (*). Regardless of the reason, JavaScript now has built in methods to add the padded characters to either the start or the end of your string. Let’s begin with the padding at the start to get the idea going.

Say you have an invoice system that needs it’s invoice numbers to be 10 characters, but you are only up to invoice number 4532. You’ll want to have six zeros prepended to the invoice number for display. To do this, we will use JavaScript’s padStart() method. This method takes two parameters: targetLength & padString. targetLength is how long the string will be once the desired number of characters have been added. padString is the character that will be used for padding; if none is supplied, JavaScript will use " " (U+0020 'SPACE').

Using the invoice example above, your code would look like this:

let invoiceNumber = "4532"
invoiceNumber.padStart(10, '0')
// Output: "0000004532"

The padEnd() method works the same way but appends the padding character to the end of the string. So, our example would look like this instead:

let invoiceNumber = "4532"
invoiceNumber.padEnd(10, '0')
// Output: "4532000000"

More Information:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd

How to subtract or add days from a Date in JavaScript?

If you have a date in JavaScript and need to subtract (or add) a number of days to that date, you will want to use JavaScript’s built in setDate() method. This will set the day of the month for a given date.

NOTE:
setDate() is based on local time. If you want to work with UTC time then use setUTCDate()

So, if you wanted to set the day of the month to be the 15th of the current month you would start with today’s date and change the date like so:

var d = new Date();
d.setDate(15);
// Sun Aug 15 2021 16:49:25 GMT-0500 (Central Daylight Time)

Using this approach combined with the getDate() method (which returns the current month’s date for a given date), you can substract or add days. If you want to get the date which is Today – 5 days then you could use:

var d = new Date();
d.setDate(d.getDate()-5);
// Tue Aug 10 2021 16:56:31 GMT-0500 (Central Daylight Time)

More Information:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getDate

How to Install Visual Studio Code on Raspberry Pi

Microsoft has a version of Visual Studio Code which will run on the Raspberry Pi OS — formerly known as Raspbian. You can even download it from the APT (Advanced Packaging Tool). And it’s simply 2 lines of code to install:

sudo apt update
sudo apt install code

Afterward, you can launch it from the Programming menu in the GUI or by typing code in the terminal.

And the really nice thing about VS Code being in the APT is that you can update it like any other package on your Pi:

sudo apt update
sudo apt upgrade code

How to get the last element in a JavaScript Array

Let’s say you have an array of numbers (but it could be an array of anything really):

const myNumbers = [1,2,3,4,5]

You want the last number in the array but don’t care how many elements are in the array. The simplest way to get the last number in the array is to get the element who’s position is the same as the length of the array minus 1. The minus 1 is because arrays are zero based, so the first element is accessed like so:

const selectedNumber = myNumbers[0]

Therefore, the easiest way to get the last element from an array without knowing how many elements are in the array is like this:

const lastNumber = myNumbers[myNumbers.length - 1]

Vue.JS — Error when clicking link, but works on second click

Had a not so obvious issue pop up recently in a Vue.JS app I’ve been working on for a while now. I have a table of members and if you click the member name, you get redirected to their profile page. There is a click event on the name link so it will store the profile id then use the router to push the new route. The issue is that when you click the link, you get the following error:

Navigation console error

BUT if you click the link a second time you get redirected to the profile page as expected. This error is basically saying you can’t navigate to the same page you are on. Which is not what I was trying to do. So I was confused.

Turns out everything was working properly in my code I just didn’t account for it all. Here is my original link:

<a href="#" @click="individualStoreKeyAndRedirect(data)">{{ data.value }}</a>

The trouble is the href=”#” is firing before my @click event fires. So, Vue’s router thinks I’m trying to go to the same page. To make the behavior what I wanted, I had to prevent that from firing and just fire my @click event.

Thankfully, Vue makes it pretty easy. Just add .prevent to your @click event. My new link looks like this:

<a href="#" @click.prevent="individualStoreKeyAndRedirect(data)">{{ data.value }}</a>

And now everything works the way I wanted and no console error!

VS Code equivalent to Visual Studio’s Ctrl+m Ctrl+o

Sometimes, when you have a long file, it’s convenient to fold/collapse all the code regions so you can get a big picture of your file. In Visual Studio (the full blown IDE from Microsoft), it’s a simple keyboard shortcut combination

Ctrl+m Ctrl+o

Thankfully, Visual Studio Code has something similar. To fold ALL regions use

Ctrl+k Ctrl+0

Then just use the following to unfold the code file

Ctrl+k Ctrl+j

The nice thing about this is that all the sub regions are folded as well. So you can simply open one region and all the items inside are still folded.

Reference: https://code.visualstudio.com/docs/getstarted/tips-and-tricks#_keyboard-reference-sheets