Constrain

Report a typo

Sometimes you need to constrain your variables. For example, all values must be within a specific range. Let's create a function newConstraint() with a closure that takes two int numbers as arguments minValue and maxValue that will serve as range delimiters, and returns an anonymous function.

The anonymous function checks if the given value is inside the defined range:

  • If the value of num is less than the minValue of the defined range, it returns minValue;
  • If the value of num is more than the maxValue of the defined range, it returns maxValue;
  • Otherwise, it returns the original value of num.

Sample Input 1:

73

Sample Output 1:

73
Write a program in Go
package main

import "fmt"

const (
Min = 0
Max = 100
)

func main() {
constraint := newConstraint(Min, Max)

var number int
fmt.Scan(&number)

fmt.Println(constraint(number))
}

func newConstraint(a, b int) ? {
minValue := a
maxValue := b

return ? {
if ? < minValue {
return minValue
}
if num > ? {
return ?
}

return num
}
}
___

Create a free account to access the full topic