Skip to content

Instantly share code, notes, and snippets.

@dfkaye
Last active November 5, 2021 18:24
Show Gist options
  • Save dfkaye/5efd1f2aa121dd611ece7688c5791ea1 to your computer and use it in GitHub Desktop.
Save dfkaye/5efd1f2aa121dd611ece7688c5791ea1 to your computer and use it in GitHub Desktop.
JavaScript version of python distutils.util.strtobool(val)
// 4 Nov 2021
// JavaScript version of python distutils.util.strtobool(val)
// Not same as https://gist.github.com/dfkaye/ce346446dee243173cd199e51b0c51ac
// see https://docs.python.org/3/distutils/apiref.html
/*
distutils.util.strtobool(val)
Convert a string representation of truth to true (1) or false (0).
True values are y, yes, t, true, on and 1;
false values are n, no, f, false, off and 0.
Raises ValueError if val is anything else.
*/
// 5 Nov 2021
// Make it more cryptic to weed out TypeScript people:
// 1. define return early
// 2. override return if argument is stringlike,
// 3. reassign lowercase in top if
// 4. replace inner ifs with ternary.
/**
* @param {any} o
* @returns {boolean|Error}
*/
function s2b(o) {
// Get string value of the argument (even if null or undefined).
var s = Object(o).valueOf();
// Define return value as an Error
var m = Error(`Unexpected value, [${s}]`);
// Visit value tests if stringlike.
if (typeof s == "string") {
// Reassign var to lowercase
s = String(s).toLowerCase();
// Override return value if either test matches...
["y", "yes", "t", "true", "on", "1"].some(v => v === s)
? m = true
: ["n", "no", "f", "false", "off", "0"].some(v => v === s)
? m = false
// ...otherwise do nothing.
: void 0;
}
return m;
}
/* test it out */
var truthy = ["t", "true", "y", "yes", "on", "1", new String("YES"), { valueOf() { return "TRUE" } }];
var falsey = ["f", "false", "n", "no", "off", "0"];
var unexpected = ["tr", "rue", "ye", "yess", "o", "one", 1, "fa", "alse", "noff", "ff", 0];
var invalid = [{}, [], null, undefined, ""];
console.group("truthy");
truthy.forEach(test => console.log({ test, result: s2b(test) }));
console.groupEnd("truthy");
// true
console.group("falsey");
falsey.forEach(test => console.log({ test, result: s2b(test) }));
console.groupEnd("falsey");
// false
console.group("unexpected");
unexpected.forEach(test => console.log({ test, result: s2b(test) }));
console.groupEnd("unexpected");
// Error
console.group("invalid");
invalid.forEach(test => console.log({ test, result: s2b(test) }));
console.groupEnd("invalid");
// Error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment