Skip to content

Code Snippets Comparisons

Ilya Sher edited this page Jan 13, 2019 · 16 revisions

This page contains random pieces of code and their counterparts in NGS, reminiscent of Rosetta Code.

I frequently feel the need to see how a piece of code would look in NGS. Here are some of the comparisons.

User Agent String Building (Go)

Original: https://github.com/moby/moby/blob/4f0d95fa6ee7f865597c03b9e63702cdcb0f7067/pkg/useragent/useragent.go

Overhead

Go

package useragent // import "github.com/docker/docker/pkg/useragent"

import (
	"strings"
)

NGS

Currently none. Maybe later, when NGS explicitly supports very large projects.

Defining the Type and Basic Operations on the Type

Go

// VersionInfo is used to model UserAgent versions.
type VersionInfo struct {
	Name    string
	Version string
}

NGS

doc VersionInfo is used to model UserAgent versions.
type VersionInfo

F init(vi:VersionInfo, name:Str, version:Str) init(args())

F Str(vi:VersionInfo) "${vi.name}/${vi.version}"

Version Info Validation

Go

func (vi *VersionInfo) isValid() bool {
	const stopChars = " \t\r\n/"
	name := vi.Name
	vers := vi.Version
	if len(name) == 0 || strings.ContainsAny(name, stopChars) {
		return false
	}
	if len(vers) == 0 || strings.ContainsAny(vers, stopChars) {
		return false
	}
	return true
}

NGS

F is_valid(vi:VersionInfo) {
	STOP_CHARS = " \t\r\n/"

	F contains_any(s:Str, chars:Str) s.any(X in chars)

	[vi.name, vi.version].all(F(field) {
		field and not(field.contains_any(STOP_CHARS))
	})
}

Creating the Full User Agent String

Go

func AppendVersions(base string, versions ...VersionInfo) string {
	if len(versions) == 0 {
		return base
	}

	verstrs := make([]string, 0, 1+len(versions))
	if len(base) > 0 {
		verstrs = append(verstrs, base)
	}

	for _, v := range versions {
		if !v.isValid() {
			continue
		}
		verstrs = append(verstrs, v.Name+"/"+v.Version)
	}
	return strings.Join(verstrs, " ")
}

NGS

F append_versions(base:Str, *version_info) {
	guard version_info.all(VersionInfo)
	not(version_info) returns base
	base +? ' ' + version_info.filter(is_valid).map(Str).join(' ')
}
Clone this wiki locally