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]

How do I update my Raspberry Pi?

It is a good idea to periodically update your Raspberry Pi so you have the most recent version of your packages and patch security vulnerabilities. The easies way to do this is thru APT (Advanced Packaging Tool).

To get started, open up a Terminal window. We will want to make sure the APT has the most recent list of available packages. So first we will run:

sudo apt update

Next, run the following command to upgrade to the latest versions available:

sudo apt full-upgrade

We use the full-upgrade rather than just the basic upgrade so that any dependencies will also be updated.

A couple things you will want to keep in mind. First, this is only for day-to-day upgrades. It does not work on major releases.

Second is that APT will not check if you have enough disk space to run. Any previously downloaded package files will be kept in /var/cache/apt/archives. But you can easily remove them by running:

sudo apt clean

Reference: https://www.raspberrypi.org/documentation/raspbian/updating.md

How to check the RAM on your Raspberry Pi

At some point you are going to want to know some information about the RAM on your Raspberry Pihow much you have, how much is used, how much is free, etc. Thankfully, there is a simple terminal command to give you this information.

Open a terminal window and enter this command:

free -h

This will give you a quick glance at the RAM usage. The -h flag will display the information in a more human readable format.