walkmap

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2021 License: MIT Imports: 1 Imported by: 1

README

Walkmap

A Go library to iterate over potentially nested map keys using the visitor pattern

Installing

go get -u github.com/affanshahid/walkmap

Usage

package main

import (
	"reflect"

	"github.com/affanshahid/walkmap"
)

func main() {
	data := map[interface{}]interface{}{
		"1": 1,
		"2": 2,
		"3": 3,
		"nested": map[interface{}]interface{}{
			"4": 4,
			"5": 5,
			"6": 6,
			"evenMoreNested": map[interface{}]interface{}{
				"7": 7,
				"8": 8,
				"9": 9,
			},
		},
	}

	walkmap.Walk(data, func(keyPath []interface{}, value interface{}, kind reflect.Kind) {
		// keyPath is the slice of keys used to arrive at the current node
		// value is the current node's value
		// kind describes the nature of the value, gotten using `reflect.TypeOf(value).Kind()`
		//...
	})
}

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Walk

func Walk(m interface{}, visitor Visitor)

Walk walks the given map `m` and calls the visitor at every non-map node

Example
data := map[interface{}]interface{}{
	"1": 1,
	"2": 2,
	"3": 3,
	"nested": map[interface{}]interface{}{
		"4": 4,
		"5": 5,
		"6": 6,
		"evenMoreNested": map[interface{}]interface{}{
			"7": 7,
			"8": 8,
			"9": 9,
		},
	},
}

concatenatePath := func(paths []interface{}) string {
	strPaths := make([]string, 0, len(paths))

	for _, path := range paths {
		strPaths = append(strPaths, path.(string))
	}

	return strings.Join(strPaths, ".")
}

flattened := map[string]interface{}{}
paths := []string{}

Walk(data, func(keyPath []interface{}, value interface{}, kind reflect.Kind) {
	pathStr := concatenatePath(keyPath)
	paths = append(paths, pathStr)
	flattened[pathStr] = value
})

sort.Strings(paths)

for _, p := range paths {
	fmt.Printf("Key: %s, Value: %d\n", p, flattened[p])
}
Output:
Key: 1, Value: 1
Key: 2, Value: 2
Key: 3, Value: 3
Key: nested.4, Value: 4
Key: nested.5, Value: 5
Key: nested.6, Value: 6
Key: nested.evenMoreNested.7, Value: 7
Key: nested.evenMoreNested.8, Value: 8
Key: nested.evenMoreNested.9, Value: 9

Types

type Visitor

type Visitor func(keyPath []interface{}, value interface{}, kind reflect.Kind)

Visitor is a function that will be called on each non-map node keyPath is a slice containing consecutive keys used to arrive at the given value value is a non-map value, corresponding to the above path kind is `reflect.TypeOf(value).Kind()`

Jump to

Keyboard shortcuts

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