Skip to content

Instantly share code, notes, and snippets.

@shimataro
Last active August 26, 2018 21:04
Show Gist options
  • Save shimataro/5cb9a13a687db90313435c9679f68dad to your computer and use it in GitHub Desktop.
Save shimataro/5cb9a13a687db90313435c9679f68dad to your computer and use it in GitHub Desktop.
再帰的なtypeof; nullや配列はobject型として判定しない
export default deepTypeof;
/**
* 再帰的なtypeof; nullや配列はobject型として判定しない
* @param {*} value 型を調べるデータ
* @returns {string} 型名
*/
function deepTypeof(value) {
const typename = typeof value;
if (value === null) {
// typeof null === "object" なので、nullは先にチェック
return "null";
}
if (Array.isArray(value)) {
// typeof [] === "object"
return _array(value);
}
if (typename === "object") {
return _object(value);
}
return typename;
}
/**
* 配列のtypeof
* @package
* @param {Array<*>} value 型を調べるデータ(配列型)
* @returns {string} 型名
*/
function _array(value) {
const types = [];
for (const v of value) {
// 各要素を再帰処理
types.push(deepTypeof(v));
}
return `[${types.join(",")}]`;
}
/**
* オブジェクトのtypeof
* @package
* @param {Object<string, *>} value 型を調べるデータ(オブジェクト型)
* @returns {string} 型名
*/
function _object(value) {
const types = [];
for (const [k, v] of Object.entries(value)) {
// 各要素を再帰処理; キーはエスケープしておく
types.push(`${JSON.stringify(k)}:${deepTypeof(v)}`);
}
return `{${types.join(",")}}`;
}
import deepTypeof from "deep-typeof";
import assert from "assert";
assert.strictEqual(deepTypeof(null), 'null');
assert.strictEqual(deepTypeof(123), 'number');
assert.strictEqual(deepTypeof('abc'), 'string');
assert.strictEqual(deepTypeof(true), 'boolean');
assert.strictEqual(deepTypeof([null, 123, 'abc', true]), '[null,number,string,boolean]');
assert.strictEqual(deepTypeof({key: 123}), '{"key":number}');
assert.strictEqual(deepTypeof({array: [null, 123], object: {key: "abc"}}), '{"array":[null,number],"object":{"key":string}}');
/* 再帰で死ぬのでこういうことはやらないように
const data = {};
data.abc = data;
deepTypeof(data);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment