Skip to content

Commit

Permalink
Add factorial handler
Browse files Browse the repository at this point in the history
  • Loading branch information
fwcd committed Jun 27, 2024
1 parent 1fff5eb commit 4677649
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
1 change: 1 addition & 0 deletions Sources/D2Handlers/D2Receiver.swift
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ public class D2Receiver: Receiver {
UniversalSummoningHandler(hostInfo: hostInfo),
HaikuHandler($configuration: $haikuConfiguration, inventoryManager: inventoryManager),
LuckyNumberHandler(luckyNumbers: [69, 42, 1337], acceptPowerOfTenMultiples: true, minimumNumberCount: 2),
FactorialHandler(),
MessageDatabaseHandler(messageDB: messageDB) // Below other handlers so as to not pick up on commands
]
reactionHandlers = [
Expand Down
32 changes: 32 additions & 0 deletions Sources/D2Handlers/Message/Handler/FactorialHandler.swift
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, *)
}
}

0 comments on commit 4677649

Please sign in to comment.