11. Message Tagger

1

Complete the tagMessages function

It should take a slice of sms messages, and a function (that takes an sms as input and returns a slice of strings) as inputs. And it should return a slice of sms messages.

  • It should loop through each message and set the tags to the result of the passed in function.

  • Be sure to modify the messages of the original slice using bracket notation messages[i].

  • Ensure the tags field contains an initialized slice. No nil slices.

2

Complete the tagger function

It should take an sms message and return a slice of strings.

  • For any message that contains "urgent" (regardless of casing) in the content, the Urgent tag should be applied first.

  • For any message that contains "sale" (regardless of casing), the Promo tag should be applied second.

"Regardless of casing" means that even "uRGent" or "SALE" should trigger the tag.

Example usage

messages := []sms{
	{id: "001", content: "Urgent! Last chance to see!"},
	{id: "002", content: "Big sale on all items!"},
	// Additional messages...
}
taggedMessages := tagMessages(messages, tagger)
// `taggedMessages` will now have tags based on the content.
// 001 = [Urgent]
// 002 = [Promo]
circle-info

The go strings package, specifically the Containsarrow-up-right and ToLowerarrow-up-right functions, can be very helpful here!

Solution

solution.go
package main
import "strings"


type sms struct {
	id      string
	content string
	tags    []string
}

func tagMessages(messages []sms, tagger func(sms) []string) []sms {
	for i, txt:= range messages{
		messages[i].tags = tagger(txt)
	}
	return messages
}

func tagger(msg sms) []string {
	tags := []string{}
	lowered := strings.ToLower(msg.content)

	if strings.Contains(lowered,"urgent"){
		tags = append(tags, "Urgent")
	}
	if strings.Contains(lowered, "sale"){
		tags = append(tags, "Promo")
	}
	return tags
}