Skip to content

Instantly share code, notes, and snippets.

@renatobenks-zz
Last active April 3, 2018 04:49
Show Gist options
  • Save renatobenks-zz/53d168cc91809d45c66f59c77f447d1c to your computer and use it in GitHub Desktop.
Save renatobenks-zz/53d168cc91809d45c66f59c77f447d1c to your computer and use it in GitHub Desktop.
self-challenge
const removeDuplicateValues = values => values.filter((number, i, array) => array.indexOf(number) === i);
const getBinaryFromNumber = number => (number >>> 0).toString(2);
const getNumbers = numbers =>
numbers.map(number => ({
binary: getBinaryFromNumber(number),
value: number,
}));
const removeStringSeparator = (string, separator) => string.split(separator).join('');
function orderByBinaryExpression(binaries, expression) {
const e = typeof expression === 'number' ? expression.toString() : expression;
return binaries
.sort(({ binary: a, value: valueA }, { binary: b, value: valueB }) => {
const _a = removeStringSeparator(a, e);
const _b = removeStringSeparator(b, e);
return _a.length > _b.length || (_a.length === _b.length && valueA > valueB);
});
}
function Rearrange(elements) {
// sort numbers by asc and remove duplicate
const numbers = removeDuplicateValues(elements);
// get binaries from numbers
const binaries = getNumbers(numbers);
// sort binaries by '1' length
const ordered = orderByBinaryExpression(binaries, 0);
// return the ordered binaries by '1' length
return ordered.map(number => parseInt(number.value, 10));
}
console.log(Rearrange([3, 1, 2, 3])); // [1, 2, 3]
console.log(Rearrange([5, 3, 7, 10, 14])); // [3, 5, 10, 7, 14]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment