Last active
June 24, 2018 18:47
-
-
Save very/66646a6992cb9910aa149f952384a1e8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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