Javascript

Javascript 한줄 함수 모음

타로 스토리 2023. 6. 12. 13:42
반응형

한줄로 구현 가능한 자바스크립트 함수 모음입니다.

원하는 기능을 만들어 놓고 필요한 경우 메서드처럼 사용하기 위한 한줄 함수들입니다.

 

 

1. 배열 중복 항목을 제거합니다.

const uniqueArr = [...new Set(arr)];

 

2. 첫글자 대문자 만들기

const capitalize = (str) => `${str.charAt(0).toUpperCase()}${str.slice(1)}`;

const name = "robert";
capitalize(name) // "Robert";

 

3. 퍼센트 계산

const calculatePercent = (value, total) => Math.round((value / total) * 100)

const questionsCorrect = 6;
const questionTotal = 11;
calculatePercent(questionsCorrect, questionsTotal); // 55%

 

4. 배열내 랜덤 값 구하기(랜덤 당첨)

const getRandomItem = (items) =>  items[Math.floor(Math.random() * items.length)];

const items = ["Nicely done!", "Good job!", "Good work!", "Correct!"];
getRandomItem(items); // "Good job!"

 

5. 배열내 중복 항목 제거

const removeDuplicates = (arr) => [...new Set(arr)];

const friendList = ["Jeff", "Jane", "Jane", "Rob"];
removeDuplicates(friendList); // ['Jeff', 'Jane', 'Rob']

 

6. 특정 속성으로 요소 정렬하기

const sortBy = (arr, key) => arr.sort((a, b) => a[key] > b[key] ? 1 : a[key] < b[key] ? -1 : 0);

const lessons = [{ position: 1, name: "Intro" }, { position: 0, name: "Basics" }];

sortBy(lessons, 'position'); 

// {position: 0, name: 'Basics'},
// {position: 1, name: 'Intro'}

 

7. 배열/객체가 같은지 확인하는 방법

const isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);

isEqual([1, '2'], [1, 2]); // false
isEqual([1, 2], [1, 2]); // true

 

8. 배열내 중복된 요소 갯수 세기

const countOccurrences = (arr, value) => arr.reduce((a, v) => (v === value ? a + 1 : a), 0);

const pollResponses = ["Yes", "Yes", "No"];
const response = "Yes";

countOccurrences(pollResponses, response); // 2

 

9. 일정시간동안 기다린후 함수 실행하기

const wait = async (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));

wait(2000).then(() => goToSignupPage());

 

10. 객체 배열에서 원하는 속성 값 추출하기

const pluck = (objs, key) => objs.map((obj) => obj[key]);

const users = [{ name: "Abe", age: 45 }, { name: "Jennifer", age: 27 }];

pluck(users, 'name'); // ['Abe', 'Jennifer']

 

11. 배열의 특정 위치에 요소 삽입

const insert = (arr, index, newItem) => [...arr.slice(0, index), newItem, ...arr.slice(index)];

const items = [1, 2, 4, 5];

// 3을 index 2에 넣기

insert(items, 2, 3); // [1, 2, 3, 4, 5]

 

12. 배열에 특정 요소가 포함되어 있는지 확인

const containsElement = array.includes(element);

 

13. 변수가 객체인지 확인

const isObject = typeof variable === 'object' && variable !== null;

 

14. 현재 날짜를 ISO 형식으로 가져오기

const currentDate = new Date().toISOString().slice(0, 10);

 

15.문자열에 하위 문자열이 포함되어 있는지 확인

const containsSubstring = string.includes(substring);

 

16.문자열의 모든항목 바꾸기

const replaceAll = (str, find, replace) => str.split(find).join(replace);

 

17.숫자를 N개의 소수점 이하 자릿수로 반올림

const roundTo = (n, decimals) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);
roundTo(123.156789, 2) // 123.16

 

18.특정길이로 문자열 자르고 '...' (말줄임) 붙이기

const truncate = (str, length) => str.length > length ? str.slice(0, length) + '...' : str;

 

19. url 알아내기

const currentUrl = () => window.location.href;
const getQueryParams = () => new URLSearchParams(window.location.search); // 쿼리 매개변수 가져오기

 

20. 숫자를 통화 형식으로 저장

const formatCurrency = (number, locale = 'en-US', currency = 'USD') => number.toLocaleString(locale, { style: 'currency', currency });

 

반응형