Skip to content

Instantly share code, notes, and snippets.

@iraniamir
Last active May 1, 2019 03:25
Show Gist options
  • Save iraniamir/9bf1fad346331e388eefd5c774bf0f6f to your computer and use it in GitHub Desktop.
Save iraniamir/9bf1fad346331e388eefd5c774bf0f6f to your computer and use it in GitHub Desktop.
Instagram, show summary email address
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Print(hideEmailAddress("[email protected]"))
}
func hideEmailAddress(email string) string {
components := strings.Split(email, "@")
username, domain := components[0], components[1]
firstCharacter, lastCharacter := string(username[0:1]), string(username[len(username)-1:])
usernameLen := len(username)
stars := strings.Repeat("*", usernameLen-2)
return firstCharacter + stars + lastCharacter + "@" + domain
}
@OmidHekayati
Copy link

It is better to improve performance by removing these unnecessary variables: username, domain, firstCharacter, lastCharacter, stars, and usernameLen. You can add some comment if you want to distinguish related components slice values and logic flow.

func HideEmailAddress(email string) string {
    // components[0] will be username part and components[1] will be domain part of email.
    var components = strings.Split(email, "@")
    // Reuse email string variable due string size is same as return size and we don't need it anymore.
    email = components[0][0:1] + strings.Repeat("*", len(components[0])-2) + components[0][len(components[0])-1:] + "@" + components[1]
    return email
}

@OmidHekayati
Copy link

After reading strings.Split API and related logic around it, I think it is so better to use strings.Index. I improve my last suggestion with this one!

// HideEmailAddress use to star username part of email except for first and last character!
func HideEmailAddress(email string) string {
	// Location of @ in email address string
	var atLocation = strings.Index(email, "@")

    	// Reuse email string variable due string size is same as return size and we don't need it anymore.
    	email = email[0:1] + strings.Repeat("*", atLocation-2) + email[atLocation-1:]

	return email
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment