Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * anagramGroup - Groups words by their anagrams
- * @param {Array} words - Words' list
- * @param {Number} words - Truncate groups with lenght lower than value
- * @returns {Array} Sorted array with groups
- * @throws {Error} Throw an error if incorrect input like non-array argument or
- * non-string value in words' list
- * @example
- * // returns [['кот', 'ток'], ['липа', 'пила']]
- * anagramGroup(['кот', 'пила', 'липа', 'пост', 'ток'])
- */
- function anagramGroup(words, minGroupSize) {
- 'use strict'
- // Arguments default value settings
- if (!minGroupSize) minGroupSize = 2
- // Arguments checking
- if (!words)
- throw new Error(`anagramGroup: arg 'words' isn't value`)
- if (!Array.isArray(words))
- throw new Error(`anagramGroup: arg 'words' isn't Array`)
- if (!words.every(word => typeof word === typeof String()))
- throw new Error(`anagramGroup: one of element inside 'words' isn't Number`)
- if (typeof minGroupSize !== typeof Number())
- throw new Error(`anagramGroup: arg 'minGroupSize' isn't Number`)
- // Map to group words by their hashes
- // key is hash (sorted words' chars)
- // value is array with words
- const wordsMap = new Set()
- // Grouping
- words.forEach(word => {
- // Calculating hash string
- const hash = word.split('').sort().join('')
- // Checking for empty value by hash
- // This situation arises when first word in the group addings
- if (!wordsMap[hash]) wordsMap[hash] = []
- // Adding word in the group by hash
- wordsMap[hash].push(word)
- })
- // Getting all groups by take only values from wordsMap
- let wordsGroups = Object.values(wordsMap)
- // Truncating groups with length lower than minGroupSize
- wordsGroups = wordsGroups.filter(group => group.length >= minGroupSize)
- // Sorting words in the groups
- wordsGroups = wordsGroups.map(group => group.sort())
- // Sorting the groups
- wordsGroups = wordsGroups.sort()
- return wordsGroups
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement