Last active
          May 22, 2024 17:10 
        
      - 
      
- 
        Save renatoaraujoc/bc933a315800b4f45e28898fae1c18ee to your computer and use it in GitHub Desktop. 
    Typesafe Singular/Plural String Builder function
  
        
  
    
      This file contains hidden or 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
    
  
  
    
  | type SingularPluralSignature = { | |
| length: number; | |
| singular: string; | |
| plural: string; | |
| ifLengthZero?: string; | |
| }; | |
| const buildSingularPluralString = (...args: Array<string | SingularPluralSignature>) => | |
| args.reduce((acc, next) => | |
| typeof next === 'string' ? [ | |
| ...acc, | |
| next | |
| ] : [ | |
| ...acc, | |
| ...(next.length > 1 ? [ | |
| next.plural | |
| ] : [ | |
| next.length === 0 && next?.ifLengthZero ? next.ifLengthZero : next.singular | |
| ]) | |
| ], [] as string[]).join('') | |
| const numberDevs = 2; | |
| const builtString = buildSingularPluralString('Oie, ', { | |
| length: numberDevs, | |
| ifLengthZero: 'não temos devs', | |
| singular: 'eu sou um dev', | |
| plural: `nós somos ${numberDevs} devs` | |
| }, '!') | |
| console.log(builtString); | 
        
      
            IgorHalfeld
  
      
      
      commented 
        May 22, 2024 
      
    
  
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment