String Compression

const stringCompression = (string) => {let str = string.split("");let count = 0;let hash = {};let result = "";}
for (let i = 0; i < str.length; i++) {}
  • If the current iteration does NOT exist in the hash, store it in the hash = to itself.
  • Then, if the current iteration and the next are not the same, increment the count variable, add the current letter to the result variable + the count, and set the count = 0.
  • Else, increment the count
for (let i = 0; i < str.length; i++) {if (!hash[str[i]]) {hash[str[i]] = str[i];
//first bullet point ^
if (str[i] !== str[i + 1]) {count++;result += str[i] + count;count = 0;
//second bullet point ^
} else {count++;
//third bullet point ^
}
  • If the current iteration DOES exist in the hash and…
  • If the current iteration and the next are not the same, increment the count variable, add the current letter to the result variable + the count, and set the count = 0.
  • Else, increment the count
else if (hash[str[i]]) {if (str[i] !== str[i + 1]) {count++;result += str[i] + count;count = 0;
//second bullet point ^
} else {count++;
//third bullet point ^
}}
if (result.length > str.length) {return str;} else {return result;}
const stringCompression = (string) => {let str = string.split("");let count = 0;let hash = {};let result = "";for (let i = 0; i < str.length; i++) {if (!hash[str[i]]) {hash[str[i]] = str[i];if (str[i] !== str[i + 1]) {count++;result += str[i] + count;count = 0;} else {count++;}} else if (hash[str[i]]) {if (str[i] !== str[i + 1]) {count++;result += str[i] + count;count = 0;} else {count++;}}}if (result.length > str.length) {return str;} else {return result;}};stringCompression("aabcccccaaa");
// returns "a2b1c5a3"

--

--

--

Flatiron student, word nerd and otter enthusiast

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Why Micro-frontends Are Amazing ?

wait for it…

Special characters for medium articles

How to Integrate Highcharts in your React analytics dashboards

Angular Material — handle many mat-error(s) in the same mat-form-field

Introduction to Promises

“My experience with MERN stack”

Arrow Functions vs Regular Functions.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Crystal Villanueva

Crystal Villanueva

Flatiron student, word nerd and otter enthusiast

More from Medium

The Power of Reduce — III

Counting the frequency of elements in a specific range (Eg: 0–9) in JavaScript

Implement Queue in C Singly Linked List

Javascript, write it clean PART 1 : variables.