CanadaTechLife

JS Utility Functions - 2026 Collection

Apr 8th, 2026
67
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // 1. Unique Array: Removes duplicates using Set
  2. const getUnique = (arr) => [...new Set(arr)];
  3.  
  4. // 2. Slugify: Converts a string to a URL-friendly slug
  5. const slugify = (str) => str.toLowerCase().trim().replace(/[^\w\s-]/g, '').replace(/[\s_-]+/g, '-');
  6.  
  7. // 3. Chunk Array: Splits an array into smaller arrays of a specific size
  8. const chunk = (arr, size) => Array.from({ length: Math.ceil(arr.length / size) }, (v, i) => arr.slice(i * size, i * size + size));
  9.  
  10. // 4. Random Range: Generates a random integer between min and max (inclusive)
  11. const randomInt = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
  12.  
  13. // 5. Omit Keys: Returns a new object without the specified keys
  14. const omit = (obj, keys) => Object.fromEntries(Object.entries(obj).filter(([key]) => !keys.includes(key)));
  15.  
  16. // 6. Deep Clone: A simple modern way to deep clone objects/arrays
  17. const deepClone = (obj) => structuredClone(obj);
  18.  
  19. // 7. Debounce: Limits how often a function can fire (useful for search inputs)
  20. const debounce = (fn, ms) => {
  21.   let timeoutId;
  22.   return (...args) => { clearTimeout(timeoutId); timeoutId = setTimeout(() => fn(...args), ms); };
  23. };
Advertisement
Comments
Add Comment
Please, Sign In to add comment