コードの設計と、それをより適切に記述する方法について、さらに質問します。コード自体は正常に機能します。
コード自体について少し説明します。この関数は、最初の引数として渡されたオブジェクトをチェックし、オブジェクトのタイプ( array
、、、など)の文字列を返すか、オブジェクトを文字列値と比較するときにブール値を返します。date
xmlhttprequest
この関数は、オブジェクトの配列を反復処理して、ブール値、ブール結果の配列、またはオブジェクトを返すこともできます。
(function ( global ) {
"use strict";
Object.type = function type( testObject, testAgainst, returnType ) {
var result, getType = function ( object ) {
var result;
if ( object && object.nodeType !== undefined ) {
result = 'dom';
}
else if ( object === global ) {
result = 'global';
}
else {
result = ({}).toString.call( object ).match( /\s([a-zA-Z]+)/ )[1].toLowerCase();
}
return result;
};
if ( getType( testAgainst ) !== 'undefined' ) {
if ( getType( testAgainst ) === 'string' ) {
return getType( testObject ) === testAgainst;
}
else if ( getType( testAgainst ) === 'array' ) {
if ( getType( returnType ) === 'undefined' ) {
returnType = 'boolean';
}
result = {
'boolean': function () {
return testObject.every(function ( member, index ) {
return getType( member ) === testAgainst[index];
});
},
'array': function () {
return testObject.map(function ( member, index ) {
return getType( member ) === testAgainst[index];
});
},
'object': function () {
var result = {};
testObject.forEach(function ( member, index ) {
result[ getType( member ) ] = getType( member) === testAgainst[index];
});
return result;
}
};
return result[ returnType ]();
}
}
return getType( testObject );
};
}( this ));
使用例:
(function () {
var objects = [null, 0, undefined, new Date(), new XMLHttpRequest(), function () {}, {}, [], 'string'],
matches = ['null', 'number', 'undefined', 'date', 'xmlhttprequest', 'function', 'object', 'array', 'string'],
misses = ['array', 'number', 'string', 'date', 'xmlhttprequest', 'function', 'object', 'number', 'string'];
console.dir({
"objects array: ": objects,
"matches array: ": matches,
"misses array: ": misses,
"Object.type( {} )": Object.type( {} ), //returns 'object'
"Object.type( 2013, 'number' )": Object.type( 2013, 'number' ), //returns true
"Object.type( objects, matches )": Object.type( objects, matches), //returns true
"Object.type( objects, misses )": Object.type( objects, misses ), //returns false
"Object.type( objects, matches, 'object' )": Object.type( objects, matches, 'object' ),
"Object.type( objects, matches, 'array' )": Object.type( objects, matches, 'array' ), //returns Array[9] (true, true, true, true, true, true, true, true, true)
"Object.type( objects, misses, 'object' )": Object.type( objects, misses, 'object' ),
"Object.type( objects, misses, 'array' )": Object.type( objects, misses, 'array' ) //returns Array[9] (false, true, false, true, true, true, true, false, true)
});
}());
主に私を悩ませている設計の問題は、コードの大部分がネストされたif
ステートメント内にあることです。
このコードを本番環境に対応させるために、どのような設計変更を加えることができますか?
編集:コメントに基づいて上記のコードを更新した要点
を作成しました( https://gist.github.com/silverstrike/5108601)