tableau icon indicating copy to clipboard operation
tableau copied to clipboard

wellknown(go): add fractionpb and comparatorpb package

Open wenchy opened this issue 1 year ago • 0 comments

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")
	}
}

wenchy avatar Sep 12 '24 04:09 wenchy