Write a function in React that converts a given string?
From:
React JS Coding Interview Questions
,
Advanced Level Coding Questions and Answers
Last Updated: 2 weeks ago
Input: "aaabbcccdd" Output: "3a2b3c2d"
// Solution 1:
function compressString(input) {
let result = '';
let count = 1;
for (let i = 1; i <= input.length; i++) {
if (input[i] === input[i - 1]) {
count++;
} else {
result += count + input[i - 1];
count = 1;
}
}
return result;
}
const inputString = "aaabbcccdd";
const compressedString = compressString(inputString);
console.log(compressedString); // Output: "3a2b3c2d"
// Solution 2:
import React from 'react';
class StringCompressor extends React.Component {
compressString(input) {
let compressedString = '';
let count = 1;
for (let i = 1; i < input.length; i++) {
if (input[i] === input[i - 1]) {
count++;
} else {
compressedString += count + input[i - 1];
count = 1;
}
}
// Handle the last set of consecutive characters
compressedString += count + input[input.length - 1];
return compressedString;
}
render() {
const inputString = 'aaabbcccdd';
const compressedString = this.compressString(inputString);
return (
<div>
Input: {inputString}
<br />
Output: {compressedString}
</div>
);
}
}
export default StringCompressor;