Skip to content

Commit

Permalink
commitlint: introduce TypeHelpers.IsInstanceOf
Browse files Browse the repository at this point in the history
The keyword `instanceof` is a footgun in JS/TS because it
only works for classes, but not primitive types.

This was taken from:
https://stackoverflow.com/a/58184883/544947
  • Loading branch information
knocte committed Sep 6, 2024
1 parent 5056f05 commit ef4ddb9
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 1 deletion.
13 changes: 13 additions & 0 deletions commitlint/fpHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,16 @@ export class OptionStatic {
}
}
}

export class TypeHelpers {
// because instanceof doesn't work with primitive types (e.g. String), taken from https://stackoverflow.com/a/58184883/544947
public static IsInstanceOf(variable: any, type: any) {
let res: boolean = false;
if (typeof type == "string") {
res = typeof variable == type.toLowerCase();
} else {
res = variable.constructor == type;
}
return res;
}
}
41 changes: 40 additions & 1 deletion commitlint/tests/testHelpers.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { test, expect } from "vitest";
import { None, Some, Option, OptionStatic } from "../fpHelpers.js";
import { None, Some, Option, OptionStatic, TypeHelpers } from "../fpHelpers.js";
const { spawnSync } = require("child_process");
const os = require("os");

Expand Down Expand Up @@ -50,6 +50,45 @@ test("testing OfObj", () => {
expect(typeGuard(ofObj2(four))).toBe("NAH");
});

class Foo {
public JustToMakeFooNonEmpty() {
return null;
}
}
class Bar {
public JustToMakeBarNonEmpty() {
return null;
}
}

test("testing TypeHelpers.IsInstanceOf", () => {
let str1 = "foo";
expect(TypeHelpers.IsInstanceOf(str1, String)).toBe(true);
let str2 = String("foo");
expect(TypeHelpers.IsInstanceOf(str2, String)).toBe(true);

//commented this one because prettier complains about it, but it works:
//let str3 = 'foo';
//expect(TypeHelpers.IsInstanceOf(str3, String)).toBe(true);

let nonStr = 3;
expect(TypeHelpers.IsInstanceOf(nonStr, String)).toBe(false);

let int1 = 2;
expect(TypeHelpers.IsInstanceOf(int1, Number)).toBe(true);
let int2 = Number(2);
expect(TypeHelpers.IsInstanceOf(int2, Number)).toBe(true);
let nonInt = "2";
expect(TypeHelpers.IsInstanceOf(nonInt, Number)).toBe(false);

let foo = new Foo();
let bar = new Bar();
expect(TypeHelpers.IsInstanceOf(foo, Foo)).toBe(true);
expect(TypeHelpers.IsInstanceOf(bar, Bar)).toBe(true);
expect(TypeHelpers.IsInstanceOf(foo, Bar)).toBe(false);
expect(TypeHelpers.IsInstanceOf(bar, Foo)).toBe(false);
});

export function runCommitLintOnMsg(inputMsg: string) {
// FIXME: should we .lowerCase().startsWith("win") in case it starts
// returning Win64 in the future? thing is, our CI doesn't like this
Expand Down

0 comments on commit ef4ddb9

Please sign in to comment.