UNPKG

my-utils-kit

Version:

A lightweight and type-safe utility library for working with strings, objects, array Performance methods in TypeScript. Includes helpful methods for deep cloning, object transformations, safe access, query string handling, and more — designed for modern J

93 lines (73 loc) 2.71 kB
const myUtils = { debounce: function (func, delay) { let timer; return function (...args) { clearTimeout(timer); timer = setTimeout(() => func(...args), delay); }; }, throttle: function (func, limit) { let last = 0; return function (...args) { let now = Date.now(); if (now - last >= limit) { last = now; func(...args); } }; }, deepClone : function(obj) { if(obj === null || typeof obj !== "object") return obj; if(obj instanceof Date) return new Date(obj); if(obj instanceof RegExp) return new RegExp(obj); if(obj instanceof Map) return new Map([...obj.entries()].map(([key, value]) => [key, deepClone(value)])); if(obj instanceof Set) return new Set([...obj].map(value => deepClone(value))); if(Array.isArray(obj)) return obj.map(item => deepClone(item)); const clone = Object.create(Object.getPrototypeOf(obj)); for(let key in obj) { if(obj.hasOwnProperty(key)){ clone[key] = deepClone(obj[key]); } } return clone; }, mergeObjects: function(obj1, obj2) { if (obj1 === null || obj2 === null || typeof obj1 !== "object" || typeof obj2 !== "object") { return obj2 !== undefined ? obj2 : obj1; } const newObj = {}; for(let key in obj1) { if(obj1.hasOwnProperty(key)){ newObj[key] = deepClone(obj1[key]); } } for(let key in obj2) { if(obj2.hasOwnProperty(key)){ if(key in newObj && typeof newObj[key] === "object" && typeof obj2[key] === "object"){ newObj[key] = mergeObjects(newObj[key], obj2[key]) } else { newObj[key] = deepClone(obj2[key]); } } } return newObj; }, chunk: function(arr, splitNum) { if(arr.length === 0 || !Array.isArray(arr) || splitNum <= 0) return arr; let result = []; for(let i = 0; i < arr.length; i+= splitNum) { result.push(arr.slice(i, i + splitNum)); } return result; }, unique: function(arr) { if(Array.isArray(arr) || arr.length === 0) return arr; return [...new Set(arr)] }, capitalize: function(str) { if(str.length === 0 || typeof str !== "string") return str; const capitalizedStr = str.replace(/\b\w/g, char => char.toUpperCase()); return capitalizedStr; } } module.exports = myUtils;