본문 바로가기
What I Read

[ Medium ] I Bet You Don't Use These JavaScript Tricks and Practices

by ウリ김영은 2023. 10. 31.

1. Using FlatMap

flatMap은 중간에 배열을 만들지 않고 한번에 하지만, filter().map()은 중간에 배열(intermediate array)을 만든다.

2023.10.31 - [FrontEnd/JavaScript] - [ JavaScript ] flatMap()

 

2. Order of Array Methods

const numbers = [9, 3, 6, 4, 8, 1, 2, 5, 7];

//before
numbers
  .sort((a, b) => a - b)
  .filter((n) => n % 2 !== 0)
  .map((n) => n ** 3);

//after
numbers
  .filter((n) => n % 2 !== 0)
  .sort((a, b) => a - b)
  .map((n) => n ** 3);

 

3. Not using reduce enough

- bad

fetch("https://jsonplaceholder.typicode.com/todos/")
  .then(res=>res.json())
  .then(todos=>{

    // using Map => an array will be build for each of the elements behind the scene
    const todosForUserMap = {};
    todos.map(todo=>{
      if (todosForUserMap[todo.userId]){
        todosForUserMap[todo.userId].push(todo);  
      }else{
        todosForUserMap[todo.userId] = [todo];
      }  
    })
  })

- good

fetch("https://jsonplaceholder.typicode.com/todos/")
  .then(res=>res.json())
  .then(todos=>{

    // using forEach
    const todosForUserMap = {};
    todos.forEach(todo=>{
      if (todosForUserMap[todo.userId]){
        todosForUserMap[todo.userId].push(todo);  
      }else{
        todosForUserMap[todo.userId] = [todo];
      }  
    })
  })

- best

fetch("https://jsonplaceholder.typicode.com/todos/")
  .then(res=>res.json())
  .then(todos=>{

    // using reduce
    const todosForUserMap = todos.reduce((accumulator, todo)=>{
      if (accumulator[todo.userId]) accumulator[todo.userId].push(todo);
      if (!accumulator[todo.userId]) accumulator[todo.userId] = [todo];
      return accumulator;
    },{})
  })

 

4. Not using Generators enough

async function *fetchProducts(){
  while (true){
    const productUrl = "https://fakestoreapi.com/products?limit=2";
    const res = await fetch(productUrl)
    const data = await res.json()
    yield data;
    // manipulate the UI here like 
    // or save it in DB or somewhere else
    // use it as a side effect place
    // even if some condition matches, break the flow
  }
}

async function main() {
  const itr = fetchProducts();
  // this should be called based on user interaction
  // or other tricks as you don't want inifinite loading.
  console.log( await itr.next() );
}

return main()

 

5. Not using native JS classes enough

//before
async function getUrl(userId, limit, category){
  return `https://fakestoreapi.com/products${category ? `/category/${category}` : ""}${limit ? Number(limit):""}${userId? Number(userId):""}`;    
}

//after => can handle complex URL-building conditions
function constructURL(category, limit, userId) {
  const baseURL = "https://fakestoreapi.com/products";
  const url = new URL(baseURL);
  const params = new URLSearchParams();

  if (category) url.pathname += `/category/${category}`;
  if (limit) params.append('limit', Number(limit).toString());
  if (userId) params.append('userId', Number(userId).toString());

  url.search = params.toString();
  return url.toString();
}

- BuilderPattern

 


원문

https://javascript.plainenglish.io/i-bet-you-dont-use-these-javascript-tricks-and-pratices-5ab5438ed4c8