add wpm-game
[small-misc-bash] / wpm-game
diff --git a/wpm-game b/wpm-game
new file mode 100755 (executable)
index 0000000..16e8da8
--- /dev/null
+++ b/wpm-game
@@ -0,0 +1,44 @@
+#!/bin/bash
+# Copyright (C) 2016 Ian Kelling
+
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+
+#     http://www.apache.org/licenses/LICENSE-2.0
+
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+wpm-game() {
+    local help="Usage: wpm-game [--help]
+Typing speed game
+
+Starts counting when you type a non-space.
+Starts over and prints the scrore when you press enter."
+    if [[ $1 == --help ]]; then
+        echo "$help"
+        return 0
+    fi
+    local x line chars seconds
+    local TIMEFORMAT=%R
+    while true
+    do
+       line=()
+       while ! [[ $line ]] || [[ $line == [[:space:]] ]] ; do
+           read -n 1 line
+       done
+       x=$( { time read line; echo "$line"; } 2>&1 )
+       seconds=${x%%[[:space:]]*}
+       x="${x#$seconds}"
+       chars=$(( ${#x} + 1 )) # +1 for the first char we don't have
+       # this formual is the same as typeracer.com's 5 keys / word
+       # wikipedia says 6 is more accurate, I like typeracers flattery.
+       # chars / 5 and seconds/60 simplifies to * 12
+       echo -ne "$(echo "12 * $chars / $seconds" | bc)\t"
+    done
+}
+wpm-game "$@"