Skip to content

luhn: add a test case #1246

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

Merged
merged 1 commit into from
May 29, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion exercises/luhn/canonical-data.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"exercise": "luhn",
"version": "1.1.0",
"version": "1.2.0",
"cases": [
{
"description": "single digit strings can not be valid",
Expand Down Expand Up @@ -105,6 +105,14 @@
"value": "091"
},
"expected": true
},
{
"description": "strings with non-digits is invalid",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How is this new case different from "valid strings with a non-digit included become invalid"?

Copy link
Contributor Author

@idealhack idealhack May 25, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

package luhn

import "strings"

func Valid(str string) bool {
	str = strings.Replace(str, " ", "", -1)
	if len(str) < 2 {
		return false
	}

	var sum = 0
	for i, ch := range str {
		val := int(ch - '0')
		if (len(str)-i)%2 == 0 {
			product := val * 2
			if product > 9 {
				product -= 9
			}
			sum += product
		} else {
			sum += val
		}
	}

	return sum%10 == 0
}

The code with a mistake above will pass current tests, but not this one.

So we have to check non-digits by adding:

if val > 9 || val < 0 {
    return false
}

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the explanation. I can see now how "valid strings with a non-digit included become invalid" passes without the new test case.

Other reviewers may ask that your new test case be moved to an earlier location in the JSON file. I'll leave that open to others to address.

@idealhack thanks for your time in improving this exercise! 👍

"property": "valid",
"input": {
"value": ":9"
},
"expected": false
}
]
}