Home >Web Front-end >JS Tutorial >avaScript One-Liners That Replace Lines of Code

avaScript One-Liners That Replace Lines of Code

DDD
DDDOriginal
2024-12-12 11:06:11602browse

avaScript One-Liners That Replace Lines of Code

We have all, at one time or another, looked at some horrid wall of JavaScript code cursing silently within ourselves, knowing pretty well that there should be a better way.

After some time spent learning, I have found some neat one-liners that will obliterate many lines of verbose code.

These are truly useful, readable tips that take advantage of modern JavaScript features for tackling common problems.

So, whether you are cleaning up code or just starting a fresh project, these tricks can help with more elegant and maintainable code.

Here are 9 such nifty one-liners you can use today.

Flattening a Nested Array

Ever tried flattening an array that goes so deep? Back in the day, that meant lots of complicated multiple loops, temporary arrays, and altogether too much code.

But now it's executed very nicely in a powerful single-liner:

const flattenArray = arr => arr.flat(Infinity);

const nestedArray = [1, [2, 3, [4, 5, [6, 7]]], 8, [9, 10]];
const cleanArray = flattenArray(nestedArray);
// Result: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

If you would do this in a more traditional way, you would have something like this:

function flattenTheHardWay(arr) {
  let result = [];
  for (let i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[i])) {
      result = result.concat(flattenTheHardWay(arr[i]));
    } else {
      result.push(arr[i]);
    }
  }
  return result;
}

All hard work is taken care of by the flat(), and adding Infinity tells it to go down to any level that it may. Simple, clean, and it works.

Object Transform: Deep Clone Without Dependencies

If you need a true deep clone of an object without pulling in lodash? Here's a zero-dependency solution that handles nested objects, arrays, and even dates:

const deepClone = obj => JSON.parse(JSON.stringify(obj));

const complexObj = {
  user: { name: 'Alex', date: new Date() },
  scores: [1, 2, [3, 4]],
  active: true
};

const cloned = deepClone(complexObj);

The old way? You'd have to type something like this:

function manualDeepClone(obj) {
  if (obj === null || typeof obj !== 'object') return obj;
  if (obj instanceof Date) return new Date(obj);

  const clone = Array.isArray(obj) ? [] : {};

  for (let key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      clone[key] = manualDeepClone(obj[key]);
    }
  }
  return clone;
}

Quick heads-up: This one-liner does have a few limitations - it won't handle functions, symbols, or circular references. But for 90% of use cases, it's pretty much spot on.

String Processing: Convert CSV to Array of Objects

This is a nice little one-liner that takes CSV data and spits out a manipulable array of objects, ideally for use in API responses or reading in data:

const csvToObjects = csv => csv.split('\n').map(row => Object.fromEntries(row.split(',').map((value, i, arr) => [arr[0].split(',')[i], value])));

const csvData = `name,age,city
Peboy,30,New York
Peace,25,San Francisco
Lara,35,Chicago`;

const parsed = csvToObjects(csvData);
// Result:
// [
//   { name: 'Peboy', age: '30', city: 'New York' },
//   { name: 'Peace', age: '25', city: 'San Francisco' },
//   { name: 'Lara', age: '35', city: 'Chicago' }
// ]

Old-fashioned? Oh, you would probably be writing something like this:

function convertCSVTheHardWay(csv) {
  const lines = csv.split('\n');
  const headers = lines[0].split(',');
  const result = [];

  for (let i = 1; i < lines.length; i++) {
    const obj = {};
    const currentLine = lines[i].split(',');

    for (let j = 0; j < headers.length; j++) {
      obj[headers[j]] = currentLine[j];
    }
    result.push(obj);
  }
  return result;
}

It's an effective way of doing data transformation with a one-liner, but add some error handling before plunging it into production.

Array Operations: Remove Duplicates and Sort

Here's a shortened one-liner that removes duplicates and sorts your array at the same time, perfect for cleaning a data set:

const uniqueSorted = arr => [...new Set(arr)].sort((a, b) => a - b);

// Example of its use:
const messyArray = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
const cleaned = uniqueSorted(messyArray);
// Result: [1, 2, 3, 4, 5, 6, 9]

// For string sorting

const messyStrings = ['banana', 'apple', 'apple', 'cherry', 'banana'];
const cleanedStrings = [...new Set(messyStrings)].sort();
// Result: ['apple', 'banana', 'cherry']

This is what the old way used to look like:

function cleanArrayManually(arr) {
  const unique = [];
  for (let i = 0; i < arr.length; i++) {
    if (unique.indexOf(arr[i]) === -1) {
      unique.push(arr[i]);
    }
  }
  return unique.sort((a, b) => a - b);
}

The Set takes care of duplicates perfectly, and then the spread operator turns it back into an array. And you just call sort() afterwards!

DOM Manipulation: Query and Transform Multiple Elements

Here's a powerful one-liner that lets you query and transform multiple DOM elements in one go:

const flattenArray = arr => arr.flat(Infinity);

const nestedArray = [1, [2, 3, [4, 5, [6, 7]]], 8, [9, 10]];
const cleanArray = flattenArray(nestedArray);
// Result: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

The traditional approach would be:

function flattenTheHardWay(arr) {
  let result = [];
  for (let i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[i])) {
      result = result.concat(flattenTheHardWay(arr[i]));
    } else {
      result.push(arr[i]);
    }
  }
  return result;
}

This works in all modern browsers and saves you from writing repetitive DOM manipulation code.

Parallel API Calls with Clean Error Handling

This is another clean line, one-liner that does parallel calls to APIs and does so in very clean error handling.

const deepClone = obj => JSON.parse(JSON.stringify(obj));

const complexObj = {
  user: { name: 'Alex', date: new Date() },
  scores: [1, 2, [3, 4]],
  active: true
};

const cloned = deepClone(complexObj);

More verbose would be:

function manualDeepClone(obj) {
  if (obj === null || typeof obj !== 'object') return obj;
  if (obj instanceof Date) return new Date(obj);

  const clone = Array.isArray(obj) ? [] : {};

  for (let key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      clone[key] = manualDeepClone(obj[key]);
    }
  }
  return clone;
}

Promise.allSettled is the hero here; it doesn't fail if one request fails and it gives back clean status information for each call.

Date/Time Formatting: Clean Date Strings Without Libraries

Here's a sweet one-liner that turns dates into clean, readable strings without any external dependencies:

const csvToObjects = csv => csv.split('\n').map(row => Object.fromEntries(row.split(',').map((value, i, arr) => [arr[0].split(',')[i], value])));

const csvData = `name,age,city
Peboy,30,New York
Peace,25,San Francisco
Lara,35,Chicago`;

const parsed = csvToObjects(csvData);
// Result:
// [
//   { name: 'Peboy', age: '30', city: 'New York' },
//   { name: 'Peace', age: '25', city: 'San Francisco' },
//   { name: 'Lara', age: '35', city: 'Chicago' }
// ]

The old-school way would look like this:

function convertCSVTheHardWay(csv) {
  const lines = csv.split('\n');
  const headers = lines[0].split(',');
  const result = [];

  for (let i = 1; i < lines.length; i++) {
    const obj = {};
    const currentLine = lines[i].split(',');

    for (let j = 0; j < headers.length; j++) {
      obj[headers[j]] = currentLine[j];
    }
    result.push(obj);
  }
  return result;
}

Intl.DateTimeFormat handles all the heavy lifting, including localization. No more manual date string building!

Event Handling: Debounce Without the Bloat

Here's a clean one-liner that creates a debounced version of any function - perfect for search input or window resize handlers:

const uniqueSorted = arr => [...new Set(arr)].sort((a, b) => a - b);

// Example of its use:
const messyArray = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
const cleaned = uniqueSorted(messyArray);
// Result: [1, 2, 3, 4, 5, 6, 9]

// For string sorting

const messyStrings = ['banana', 'apple', 'apple', 'cherry', 'banana'];
const cleanedStrings = [...new Set(messyStrings)].sort();
// Result: ['apple', 'banana', 'cherry']

The traditional way would look like this:

function cleanArrayManually(arr) {
  const unique = [];
  for (let i = 0; i < arr.length; i++) {
    if (unique.indexOf(arr[i]) === -1) {
      unique.push(arr[i]);
    }
  }
  return unique.sort((a, b) => a - b);
}

This one-liner covers all basic debouncing use cases and saves you from calling functions unnecessarily, especially when inputs are generated in rapid succession like typing or resizing.

Local Storage: Object Storage with Validation

Here's just another clean one-liner that handles object storage in localStorage with built-in validation and error handling:

const modifyElements = selector => Array.from(document.querySelectorAll(selector)).forEach(el => el.style);

// Use it like this:
const updateButtons = modifyElements('.btn')
  .map(style => Object.assign(style, {
    backgroundColor: '#007bff',
    color: 'white',
    padding: '10px 20px'
}));

// Or even simpler for class updates:
const toggleAll = selector => document.querySelectorAll(selector).forEach(el => el.classList.toggle('active'));

The old way would need something like this:

function updateElementsManually(selector) {
  const elements = document.querySelectorAll(selector);
  for (let i = 0; i < elements.length; i++) {
    const el = elements[i];
    el.style.backgroundColor = '#007bff';
    el.style.color = 'white';
    el.style.padding = '10px 20px';
  }
}

The wrapper gives you a clean API for localStorage operations and handles all the JSON parsing/stringify automatically.

Wrapping Up

These one-liners aren't just about writing less code – they're about writing smarter code. Each one solves a common JavaScript challenge in a clean, maintainable way. While these snippets are powerful, remember that readability should always come first. If a one-liner makes your code harder to understand, break it down into multiple lines.

Feel free to mix and match these patterns in your projects, and don't forget to check browser compatibility for newer JavaScript features like flat() or Intl.DateTimeFormat if you're supporting older browsers.

Got your own powerful JavaScript one-liners? I'd love to see them!

Follow me on X for more JavaScript tips, tricks, and discussions about web development. I regularly share code snippets and best practices that make our dev lives easier.

Stay curious, keep coding, and remember: good code is not about how little you write, but how clearly you express your intent.

The above is the detailed content of avaScript One-Liners That Replace Lines of Code. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn