JSFiddle - React, Tailwind, and code Playground
by AntonLapshin
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Coding challenge</title>
<link rel="stylesheet" href="https://code.jquery.com/qunit/qunit-2.9.2.css">
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
<script src="https://code.jquery.com/qunit/qunit-2.9.2.js"></script>
</body>
</html>
JavaScript
const countChar = (acc, c) => {
acc[c] = (acc[c] || 0) + 1;
return acc;
}
const shiftCharLeft = counts => (acc, c, i) => {
let j = i;
while (j > 0 && counts[acc[j - 1]] < counts[acc[j]]) {
const temp = acc[j - 1];
acc[j - 1] = acc[j];
acc[j--] = temp;
}
return acc;
}
const uniqCharsDesc = input => {
const counts = [].reduce.call(input, countChar, {})
const uniqChars = Object.keys(counts);
return uniqChars.reduce(shiftCharLeft(counts), uniqChars).join('');
}
[
['hello world', 'lohe wrd'],
['', ''],
['a', 'a'],
['aaaaaaa', 'a'],
['abb', 'ba'],
['a a b b ', ' ab']
].forEach(([input, output]) =>
QUnit.test(`"${input}" => "${output}"`, assert => {
assert.equal(uniqCharsDesc(input), output);
})
)