Last active
August 26, 2018 21:04
-
-
Save shimataro/5cb9a13a687db90313435c9679f68dad to your computer and use it in GitHub Desktop.
再帰的なtypeof; nullや配列はobject型として判定しない
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(",")}}`; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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