Skip to content

Instantly share code, notes, and snippets.

@very
Last active June 24, 2018 18:47
Show Gist options
  • Save very/66646a6992cb9910aa149f952384a1e8 to your computer and use it in GitHub Desktop.
Save very/66646a6992cb9910aa149f952384a1e8 to your computer and use it in GitHub Desktop.
// Put strings from the input array
// which can be rotated to match each other
// into groups.
//
// input: ['Hello', 'World', 'lohEl', 'orld']
// output: [['Hello', 'lohEl'], ['World'], ['orld']]
function groupRotations(strings, transform) {
if (typeof transform !== 'function') {
transform = string => string.toLowerCase();
}
const buckets = []; // contains all buckets in the correct order
const bucketMap = new Map(); // maps all possible rotations to the correct bucket
strings.forEach(string => {
const transformed = String(transform(string));
const bucket = bucketMap.get(transformed) || [];
if (bucket.length === 0) {
// a new bucket!
buckets.push(bucket);
for (let i = 0; i < transformed.length; ++i) {
bucketMap.set(transformed.slice(i) + transformed.slice(0, i), bucket);
}
}
bucket.push(string); // regardless
});
return buckets;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment