JSFiddle - React, Tailwind, and code Playground

by Abdul Ahmad

JavaScript

// - all lowercase alpha
// 'aaabbcccddaabcccccd'
// 'a3b2c3d2a2bc5d'
// - track all letters
// - keep order
// - track count
// - return value is string

function useDebounce(cb, dep, timeout = 300) {
	const timeoutId = useRef();
  
  const retFunc = useCallback(() => {
  	clearTimeout(timeoutId.current);
    timeoutId.current = setTimeout(cb, timeout);
  }, dep);
  
  return retFunc;
}


function SomeComponent() {
	const [search, setSearch] = useState('');
	const debounce = useDebounce();
  
  const onChange = useCallback((e) => {
  	setSearch(e.target.value);
  }, []);
  
  useEffect(() => {
  	debounce(() => {
    	// fetch search data
      
    });
  }, [search]);
}

function doSomething(str) {
	let currLetter = '';
  let count = 0;
  let finalString = '';

	for (let i = 0; i < str.length; i++) {
		const letter = str.charAt(i);  
    
    if (letter !== currLetter) {
    	currLetter = letter;
      let nextStringPortion = letter;
      
      if (i !== 0) nextStringPortion = getActualCount(count) + letter;
      
      finalString += nextStringPortion;
      
      count = 0;
    }
    
    count++;
  
  }
  
  finalString += getActualCount(count);
  
  return finalString;

}

function getActualCount(count) {
  if (count > 1) return count;
  return '';
}

const res = doSomething('aaabbcccddaabcccccd');
console.log(res);