ch5ex1

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.1
// Refs:
:url-base: https://github.com/fenegroni/TGPL-exercise-solutions
:workflow: workflows/Exercise 5.1
:action: actions/workflows/ch5ex1.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}

Change the `findlinks` program to traverse the `n.FirstChild` linked list
using recursive calls to `Visit` instead of a loop.

== Test

The implementation validates that given an HTML document with
zero, one, or more links,
they are all still returned by the new recursive implementation,
as they were returned by the original implementation.

=== Original implementation

The book's implementation of `Visit` uses a for-loop to visit `c.NextSibling` within the sub-node:

[source,go]
----
for c := n.FirstChild; c != nil; c = c.NextSibling {
	links = Visit(links, c)
}
----

=== Fully-recursive implementation

The solution to the exercise uses no such for loop.

`Visit` now recursively calls itself with the correct parameters:

[source,go]
----
return Visit(Visit(links, n.FirstChild), n.NextSibling)
----

== Example

Given this example HTML document as input:

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

the Example function's `Output` is:

[source,go]
----
// Output:
// link1
// link2
----

Documentation

Overview

Exercise5.1 prints the links in an HTML document read from standard input.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Visit

func Visit(links []string, n *html.Node) []string

Visit appends to links each link found in n and returns the result.

Example
document := `<html>
	<head></head>
	<body>
		<a href="link1">a</a>
		<a href="link2">b</a>
	</body>
</html>`
parseTree, _ := html.Parse(strings.NewReader(document))
for _, link := range Visit(nil, parseTree) {
	fmt.Println(link)
}
Output:

link1
link2

Types

This section is empty.

Jump to

Keyboard shortcuts

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