github.com/blend/go-sdk@v1.20220411.3/stringutil/compress_whitespace.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package stringutil
     9  
    10  import (
    11  	"strings"
    12  	"unicode"
    13  )
    14  
    15  // CompressSpace compresses whitespace characters into single spaces.
    16  // It trims leading and trailing whitespace as well.
    17  func CompressSpace(text string) (output string) {
    18  	if text == "" {
    19  		return
    20  	}
    21  
    22  	var state int
    23  	for _, r := range text {
    24  		switch state {
    25  		case 0: // non-whitespace
    26  			if unicode.IsSpace(r) {
    27  				state = 1
    28  			} else {
    29  				output = output + string(r)
    30  			}
    31  		case 1: // whitespace
    32  			if !unicode.IsSpace(r) {
    33  				output = output + " " + string(r)
    34  				state = 0
    35  			}
    36  		}
    37  	}
    38  
    39  	output = strings.TrimSpace(output)
    40  	return
    41  }