Skip to content

Commit

Permalink
Merge pull request #10 from goctus/issue/#7
Browse files Browse the repository at this point in the history
Add `NativeMap`
  • Loading branch information
kerelape committed Apr 17, 2023
2 parents ec3a0a1 + 6584244 commit df1f3d5
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 0 deletions.
4 changes: 4 additions & 0 deletions pkg/map.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@

package collection

import "errors"

var ErrNotFound = errors.New("key not found")

// Map is an associated collection.
type Map[K any, V any] interface {
Collecton[K, V]
Expand Down
72 changes: 72 additions & 0 deletions pkg/native_map.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*
* MIT License
*
* Copyright (c) 2023-present goctus
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

package collection

import option "github.com/goctus/option/pkg"

// NativeMap is Map that uses Go's map.
type NativeMap[K, V any] struct {
origin map[any]V
}

// NewNativeMap creates a new NativeMap.
func NewNativeMap[K, V any](origin map[any]V) NativeMap[K, V] {
return NativeMap[K, V]{origin}
}

func (nm NativeMap[K, V]) Size() int {
return len(nm.origin)
}

func (nm NativeMap[K, V]) Found(key K) option.Option[V] {
value, ok := nm.origin[key]
if !ok {
return option.NewNone[V](ErrNotFound)
}
return option.NewSome(value)
}

func (nm NativeMap[K, V]) With(key K, value V) Map[K, V] {
copy := nm.clone()
copy[key] = value
return NativeMap[K, V]{copy}
}

func (nm NativeMap[K, V]) Without(key K) Map[K, V] {
if _, contains := nm.origin[key]; !contains {
return nm
}
copy := nm.clone()
delete(copy, key)
return NativeMap[K, V]{copy}
}

func (nm NativeMap[K, V]) clone() (result map[any]V) {
result = make(map[any]V)
for k, v := range nm.origin {
result[k] = v
}
return
}

0 comments on commit df1f3d5

Please sign in to comment.