对可能降低复杂性的方法的随机思考:
这里真正的限制因素将是您可以如何减少类型集。最明显的方法之一是仅基于对象的键来做某事。数据中有额外键的问题是我们不能只依赖Object.keys( data ).sort().join(",")
,我们还必须尝试我们拥有的每个键组合。
// Assuming the "types" list is called "types":
// using underscore.js api
var _ = require('underscore');
var keyMap = _.chain( types ).map(function( typeDef, typeIndex ) {
// get an index with the definition, in case its
return { index: typeIndex, def: typeDef };
}).groupBy(function( data ) {
return _.keys( data.def ).sort().join(",");
}).value();
// empty map needed
keyMap[""] = [];
// assumes sorted key list
function getPossibleMaps( keys ) {
// if we have a map for this, use it
if ( keyMap[ keys.join(",") ] ) {
return keyMap[ keys.join(",") ];
} else {
// create a map of possible types by removing every key from the list of keys
// and then looking for maps that match, cache our result
return keyMap[ keys.join(",") ] = recursiveMapTest( keys );
}
}
function recursiveMapTest( keys ) {
return _.chain( keys )
.map(function( key ) {
return getPossibleMaps( _.without( keys, key ) );
}).flatten().value();
}
// we must also include "lesser" definitions for each of the key lists we found:
_.each( keyMap, function( results, index ) {
var keys = index.split(",");
keyMap[index] = results.concat( recursiveMapTest( keys ) );
});
function getType( data ) {
function checkType( typeData ) {
var def = typeData.def;
return _.every(typeData.def, function( value, key ) {
// these checks are probably not quite right
if ( value === null ) {
return true;
} else if ( value === Number ) {
return typeof data[key] === "number" || data instanceof Number;
} else if ( value === String ) {
return typeof data[key] === "string" || data instanceof String;
} else {
return data[ key ] === value;
}
});
}
var match = _.find( getPossibleMaps( _.keys( data ).sort() ), checkType );
return match && match.index;
}
// Retrieve
var clientTypes = [
{ type: 1, name: 'user', password: 'pass' },
{ type: 2, name: 'user', password: 'pass' },
{ type: 2, user_id: 5, action: 'hello' },
{ type: 2, object_id: 5, action: 'hello' },
{ type: 1, name: 'user', password: 'pass', remember_me: true }
];
console.log('Client types:');
for (var i = 0; i < clientTypes.length; i++) {
var type = clientTypes[i];
// The type object from the map
console.log("getType", type, getType(type));
}
jsbin
当然,这只是意味着可能的传入键列表越多,存储“快速”查找表所消耗的内存就越多。
此外,如果一切都有数字类型,您显然可以使用它来加速该子类型中可能的“对象类型”的一大块。
我认为你最好的选择是首先避免需要做任何这些。使用您的对象传递更好的类型提示。