ch5ex2

package
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 5, 2022 License: GPL-3.0 Imports: 1 Imported by: 0

README

= Exercise 5.2
// Refs:
:url-base: https://github.com/fenegroni/TGPL-exercise-solutions
:workflow: workflows/Exercise 5.2
:action: actions/workflows/ch5ex2.yml
:url-workflow: {url-base}/{workflow}
:url-action: {url-base}/{action}
:badge-exercise: image:{url-workflow}/badge.svg?branch=main[link={url-action}]

{badge-exercise}

Write a function to populate a mapping from element names
- `p`, `div`, `span` and so on -
to the number of elements with that name in an HTML document tree

== Test

I wrote a function called `CountElements`,
very similar to `visit` in exercise 5.1.

The test is also very similar to the one in exercise 5.1,
except it uses a map between elements and their count.

[source,go]
----
struct {
	document string
	want     map[string]int
}
----

== Example

Given this example HTML document as input:

[source,html]
----
<html>
    <head></head>
    <body>
        <a href="link1">a</a>
        <p>
            <a href="link2">b</a>
        </p>
        <a href="link3">c</a>
    </body>
</html>
----

An `// Unordered output:` comment is necessary:
when printing the map contents,
there is no guarantee the order in which the elements are stored in it:
`<a>` can appear before or after `<p>`.

[source,go]
----
// Unordered output:
// <a>: 3
// <p>: 1
----

Documentation

Overview

Exercise5.2 prints a count of all the elements in an HTML document read from standard input.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func CountElements

func CountElements(elements map[string]int, n *html.Node)

CountElements populates elements with element names (p, div, span and so on) and the number of elements with that name found in n.

Example
document := `<html>
	<head></head>
	<body>
		<a href="link1">a</a>
		<p>
			<a href="link2">b</a>
		</p>
		<a href="link3">c</a>
	</body>
</html>`
parseTree, _ := html.Parse(strings.NewReader(document))
elements := map[string]int{}
CountElements(elements, parseTree)
for name, count := range elements {
	fmt.Printf("<%s>: %d\n", name, count)
}
Output:

<a>: 3
<p>: 1

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL