Skip to content

Instantly share code, notes, and snippets.

@wperron
Created May 30, 2023 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wperron/19d0cdd19bba9b51a522dc0f3fc56780 to your computer and use it in GitHub Desktop.
Save wperron/19d0cdd19bba9b51a522dc0f3fc56780 to your computer and use it in GitHub Desktop.
const rows = [
"qwertyuiop",
"asdfghjkl",
"zxcvbnm",
].reduce(
(acc, curr, i) => {
curr.split('').forEach(c => acc[c] = i);
return acc;
},
{},
);
/**
* Returns a boolean showing whether the word `s` can be typed on a single row
* given a standard ANSI layout keyboard.
*
* @param s string
* @return bool
*/
export function singleRow(s) {
let curr = rows[s[0]];
for (let c of s.split('')) {
if (curr != rows[c]) {
return false;
}
}
return true;
}
if (import.meta.main) {
console.log(Deno.args[0]);
console.log(singleRow(Deno.args[0] ?? ""));
}
import { singleRow } from "./keyboard_row.js";
// Assumes MacOS for the location of the dictionary file
const words = Deno.readTextFileSync("/usr/share/dict/web2").split('\n');
Deno.bench("singleRow", () => {
for (let w of words) {
singleRow(w);
}
});
// Results
// cpu: Apple M1 Pro
// runtime: deno 1.34.1 (aarch64-apple-darwin)
//
// file:///REDACTED/keyboard-row_test.js
// benchmark time (avg) (min … max) p75 p99 p995
// ------------------------------------------------- -----------------------------
// singleRow 11.23 ms/iter(11.11 ms … 11.64 ms) 11.26 ms 11.64 ms 11.64 ms
import { singleRow } from "./keyboard_row.js";
import { assert, assertFalse } from "https://deno.land/std@0.190.0/testing/asserts.ts";
Deno.test("single row words", () => {
assert(singleRow("typewriter"));
});
Deno.test("multi row words", () => {
assertFalse(singleRow("fantastic"));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment