Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

wellknown(go): add fractionpb and comparatorpb package #143

Open
wenchy opened this issue Sep 12, 2024 · 0 comments
Open

wellknown(go): add fractionpb and comparatorpb package #143

wenchy opened this issue Sep 12, 2024 · 0 comments

Comments

@wenchy
Copy link
Member

wenchy commented Sep 12, 2024

See https://github.com/protocolbuffers/protobuf-go/blob/master/types/known/timestamppb/timestamp.pb.go

For encapsulating common util functions, such as:

package fractionpb

import (
	"github.com/tableauio/tableau/proto/wellknownpb"
)

// New creates a new fraction.
func New(num, den int32) *tableaupb.Fraction {
	return &tableaupb.Fraction{Num: num, Den: den}
}

// NewInteger creates a new special fraction: integer. When a fraction has a denominator
// of 1 (e.g.: a/1), it is referred to as a whole number or an integer.
func NewInteger(num int32) *tableaupb.Fraction {
	return New(num, 1)
}

// NewComparator creates a new fraction comparator.
func NewComparator(sign tableaupb.Comparator_Sign, num, den int32) *tableaupb.Comparator {
	return &tableaupb.Comparator{
		Sign:  sign,
		Value: New(num, den),
	}
}
package fractionpb

import (
	"github.com/tableauio/tableau/proto/wellknownpb"
)

func Compare(left *tableaupb.Fraction, cmp *tableaupb.Comparator) bool {
	right := cmp.GetValue()
	// cross-multiply to compare
	lval := left.GetNum() * right.GetDen()
	rval := right.GetNum() * left.GetDen()
	switch cmp.GetSign() {
	case tableaupb.Comparator_SIGN_EQUAL:
		return lval == rval
	case tableaupb.Comparator_SIGN_NOT_EQUAL:
		return lval != rval
	case tableaupb.Comparator_SIGN_LESS:
		return lval < rval
	case tableaupb.Comparator_SIGN_LESS_OR_EQUAL:
		return lval <= rval
	case tableaupb.Comparator_SIGN_GREATER:
		return lval > rval
	case tableaupb.Comparator_SIGN_GREATER_OR_EQUAL:
		return lval >= rval
	default:
		panic("invalid compare operator")
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant