-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
33 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
import Utils | ||
import D2MessageIO | ||
|
||
fileprivate let factorialPattern = #/\b(?<operand>\d+)!\b/# | ||
|
||
public struct FactorialHandler: MessageHandler { | ||
private let operandRange: Range<Int> | ||
|
||
public init(operandRange: Range<Int> = 3..<171) { | ||
self.operandRange = operandRange | ||
} | ||
|
||
public func handle(message: Message, sink: any Sink) -> Bool { | ||
if let channelId = message.channelId, | ||
let author = message.author, | ||
!author.bot { | ||
let matches = message.content.matches(of: factorialPattern) | ||
if matches.count == 1, | ||
let match = matches.first, | ||
let operand = Int(match.operand), | ||
operandRange.contains(operand) { | ||
let result = factorial(operand) | ||
sink.sendMessage("\(operand)! = \(result.isLessThanOrEqualTo(Double(Int.max)) ? String(Int(result)) : String(result))", to: channelId) | ||
} | ||
} | ||
return false | ||
} | ||
|
||
private func factorial(_ n: Int) -> Double { | ||
(1...n).map(Double.init).reduce(1, *) | ||
} | ||
} |