Blog#81: What is the Immutability Pattern in JavaScript?

image.png

Để giúp các bạn có thể nâng cao trình độ tiếng Anh, Blog này mình sẽ viết bằng tiếng Anh.

Mục tiêu sẽ là, sử dụng Technical Document để học Tiếng Anh. Mình sẽ cố gắng sử dụng ngữ pháp và từ vựng đơn giản nhất (level~A1/A2) để giúp các bạn đọc nó dễ dàng hơn.


Hi, I'm Tuan, a Full-stack Web Developer from Tokyo 😊. Follow my blog to not miss out on useful and interesting articles in the future.

The immutability pattern is a way of designing code that relies on not changing the value of a piece of data once it has been created. This can be especially useful in functional programming, as it allows you to write code that is easier to reason about and debug.

Why Use the Immutability Pattern?

There are several benefits to using the immutability pattern in your code:

  1. It helps prevent accidental changes to data, which can lead to hard-to-track-down bugs.
  2. It allows you to write code that is easier to understand, as it clearly defines the input and output of each function.
  3. It can improve the performance of your code, as immutable data structures can be more efficiently implemented and optimized by JavaScript engines.

Example

Storing application state

In a large application, it can be useful to store the state of the app in a single, immutable object. This makes it easy to track changes to the state over time and debug any issues that may arise.

const initialState = {
  user: {
    name: 'John',
    age: 30
  },
  todos: []
}

function updateUser(state, user) {
  return {
    ...state,
    user
  }
}

const newState = updateUser(initialState, { name: 'Jane', age: 25 })
// newState: { user: { name: 'Jane', age: 25 }, todos: [] }

Managing a list of items

When working with lists of items, it can be useful to use immutable data structures to avoid accidental changes to the list.

const initialList = [1, 2, 3, 4]

function addItem(list, item) {
  return [...list, item]
}

const newList = addItem(initialList, 5)
// newList: [1, 2, 3, 4, 5]

Implementing undo/redo functionality:

The immutability pattern can be especially useful when implementing undo/redo functionality, as it allows you to easily track changes to data over time.

let currentState = {
  user: {
    name: 'John',
    age: 30
  }
}

const history = []

function updateUser(state, user) {
  history.push(state)
  return {
    ...state,
    user
  }
}

currentState = updateUser(currentState, { name: 'Jane', age: 25 })
// currentState: { user: { name: 'Jane', age: 25 } }

function undo() {
  currentState = history.pop()
}

undo()
// currentState: { user: { name: 'John', age: 30 } }

Validating user input

When validating user input, it can be useful to create a new, immutable version of the input data rather than changing the original data.

function validateInput(input) {
  const errors = []

  if (!input.name) {
    errors.push('Name is required')
  }
  if (!input.email) {
    errors.push('Email is required')
  }
  if (!input.password) {
    errors.push('Password is required')
  }

  return {
    ...input,
    errors
  }
}

const validatedInput = validateInput({ name: 'John', email: 'john@example.com' })
// validatedInput: { name: 'John', email: 'john@example.com', errors: ['Password is required'] }

Creating a report

When creating a report, it can be useful to create an immutable version of the data rather than modifying the original data.

const data = [
  { name: 'John', age: 30 },
  { name: 'Jane', age: 25 },
  { name: 'Bob', age: 35 }
]

function createReport(data) {
  const report = {
    total: data.length,
    averageAge: data.reduce((sum, item) => sum + item.age, 0) / data.length
  }

  return {
    ...data,
    report
  }
}

const reportData = createReport(data)
  // reportData: [
  // { name: 'John', age: 30, report: { total: 3, averageAge: 30 } },
  // { name: 'Jane', age: 25, report: { total: 3, averageAge: 30 } },
  // { name: 'Bob', age: 35, report: { total: 3, averageAge: 30 } }
  // ]

Conclusion

The immutability pattern can be a useful tool for designing code that is easy to reason about and debug. By using this pattern, you can create code that is more predictable and easier to understand, which can ultimately lead to more maintainable and scalable applications.

As always, I hope you enjoyed this article and learned something new. Thank you and see you in the next articles!

If you liked this article, please give me a like and subscribe to support me. Thank you. 😊

NGUYỄN ANH TUẤN

Xin chào, mình là Tuấn, một kỹ sư phần mềm đang làm việc tại Tokyo. Đây là blog cá nhân nơi mình chia sẻ kiến thức và kinh nghiệm trong quá trình phát triển bản thân. Hy vọng blog sẽ là nguồn cảm hứng và động lực cho các bạn. Hãy cùng mình học hỏi và trưởng thành mỗi ngày nhé!

Đăng nhận xét

Mới hơn Cũ hơn