jkulvich

anagramGroup func eng ver

Jun 20th, 2021
625
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * anagramGroup - Groups words by their anagrams
  3.  * @param   {Array}  words - Words' list
  4.  * @param   {Number} words - Truncate groups with lenght lower than value
  5.  * @returns {Array}  Sorted array with groups
  6.  * @throws  {Error}  Throw an error if incorrect input like non-array argument or
  7.  *                   non-string value in words' list
  8.  * @example
  9.  * // returns [['кот', 'ток'], ['липа', 'пила']]
  10.  * anagramGroup(['кот', 'пила', 'липа', 'пост', 'ток'])
  11.  */
  12. function anagramGroup(words, minGroupSize) {
  13.     'use strict'
  14.  
  15.     // Arguments default value settings
  16.     if (!minGroupSize) minGroupSize = 2
  17.  
  18.     // Arguments checking
  19.     if (!words)
  20.         throw new Error(`anagramGroup: arg 'words' isn't value`)
  21.    if (!Array.isArray(words))
  22.        throw new Error(`anagramGroup: arg 'words' isn't Array`)
  23.     if (!words.every(word => typeof word === typeof String()))
  24.         throw new Error(`anagramGroup: one of element inside 'words' isn't Number`)
  25.    if (typeof minGroupSize !== typeof Number())
  26.        throw new Error(`anagramGroup: arg 'minGroupSize' isn't Number`)
  27.  
  28.     // Map to group words by their hashes
  29.     // key is hash (sorted words' chars)
  30.     // value is array with words
  31.     const wordsMap = new Set()
  32.  
  33.     // Grouping
  34.     words.forEach(word => {
  35.         // Calculating hash string
  36.         const hash = word.split('').sort().join('')
  37.         // Checking for empty value by hash
  38.         // This situation arises when first word in the group addings
  39.         if (!wordsMap[hash]) wordsMap[hash] = []
  40.         // Adding word in the group by hash
  41.         wordsMap[hash].push(word)
  42.     })
  43.  
  44.     // Getting all groups by take only values from wordsMap
  45.     let wordsGroups = Object.values(wordsMap)
  46.  
  47.     // Truncating groups with length lower than minGroupSize
  48.     wordsGroups = wordsGroups.filter(group => group.length >= minGroupSize)
  49.     // Sorting words in the groups
  50.     wordsGroups = wordsGroups.map(group => group.sort())
  51.     // Sorting the groups
  52.     wordsGroups = wordsGroups.sort()
  53.  
  54.     return wordsGroups
  55. }
RAW Paste Data