logo

Sorting Objects in Ascending Order, Comparing Objects for Equality

  • Sorting an Object’s Keys in Ascending Order
function sortObjectByKeys(obj) {
    return Object.keys(obj)
        .sort() // Sort keys in ascending order
        .reduce((sortedObj, key) => {
            sortedObj[key] = obj[key];
            return sortedObj;
        }, {});
}
  • Sorting an Object’s Keys in Descending Order
function sortObjectByKeysDescending(obj) {
  return Object.keys(obj)
    .sort((a, b) => b.localeCompare(a)) // Sort keys in descending order
    .reduce((sortedObj, key) => {
      sortedObj[key] = obj[key]; // Insert into new object in the order of sorted keys
      return sortedObj;
    }, {});
}
  • Comparing Two Objects for Equality of Keys and Values
function areObjectsEqual(obj1, obj2) {
    if (Object.keys(obj1).length !== Object.keys(obj2).length) return false;
    for (let key in obj1) {
        if (obj1[key] !== obj2[key]) return false;
    }
    return true;
}
One minute to read

How to Enable openSSL Legacy Mode

After upgrading Node.js, you may encounter errors when loading scripts.

If you’re seeing openSSL errors, try enabling legacy mode as follows:

export NODE_OPTIONS=--openssl-legacy-provider

"scripts": {
  "build": "NODE_OPTIONS=--openssl-legacy-provider webpack --mode production"
}
One minute to read

Floating-Point Numbers

In JavaScript, floating-point numbers are represented using the 64-bit floating-point format defined by the IEEE 754 standard.

Some numbers cannot be represented exactly, which can lead to errors.

Issues with Floating-Point Numbers

  1. Limitations of Binary Representation: Some decimal fractions cannot be represented exactly in binary form. For example, numbers like 0.1 or 0.2 become repeating decimals when converted to binary floating-point and are stored as approximations.
console.log(0.1 + 0.2); // 예상: 0.3, 실제: 0.30000000000000004
  1. Loss of Precision: Small errors during calculations can accumulate into significant errors. This is particularly problematic in iterative calculations or financial computations.

Solutions

  1. Using the toFixed() Method

The toFixed() method rounds a number to a specified number of decimal places and returns it as a string.

2 minutes to read