I have some rules lookups that are based on state.. I am trying to think of a way to make accessing these easy without setting up some sort of intermediate step.
I'm imagining something like:
rules = {
['AK','FL','NY']: {a: 278},
['CA','LA','TX']: {a: 422}
}
console.log(rules['AK']); //278
console.log(rules['TX']); //422
I know that's not possible.. but wondering what the simplest way to achieve something like that would be
Take a page from MySQL's foreign key :
var states = {
'AK' : 1,
'FL' : 1,
'NY' : 1,
'CA' : 2,
'LA' : 2,
'TX' : 2
}
var rules = {
1 : 278,
2 : 422
}
Then you can reference the rules like so :
console.log(rules[states['AK']]);
I know this is an ad-hoc solution. Just wanted to share it anyway.
function Store() {
var cache = {};
this.set = function(key, value) {
var k = JSON.stringify(key);
cache[k] = value;
};
this.get = function(key) {
for(var k in cache) {
if(cache.hasOwnProperty(k)) {
var _k = JSON.parse(k);
if(_k.indexOf(key) !== -1) return cache[k];
}
}
return null;
}
}
var store = new Store;
store.set(['AK','FL','NY'], {a:278});
store.get('AK'); // returns {a:278}
Affect Keys with same rule :
var rule1 = {a : 278};
var rule2 = {a : 422};
var rules = {
'AK' : rule1,
'FL' : rule1,
'NY' : rule1,
'CA' : rule2,
'TX' : rule2
};
console.log(rules['AK']); // {a:278}
console.log(rules['AK'].a); // 278
If you really want something close to the structure you show, define rules
as an array:
var rules = [
[['AK','FL','NY'], {a: 278}],
[['CA','LA','TX'], {a: 422}]
];
However, accessing this is going to be bit cumbersome:
function find_rule(state) {
for (var [states, rule] of rules) {
if (states.indexOf(state) >= 0) return rule;
}
return -1;
}
Or without ES6:
function find_rule(state) {
for (var i = 0; i < rules.length; i++) {
var rule = rules[i];
if (rule[0].indexOf(state) >= 0) return rule[1];
}
return -1;
}
var rules = { "['AK','FL','NY']": {a: 278}, "['CA','LA','TX']": {a: 422} }; var key = 'AK'; key = Object.keys(rules).filter(function (val) { return val.indexOf(key) !== -1; }).join(","); console.log("result: ", rules[key]);//result: {a: 278} console.log("key: ", JSON.parse(key.replace(/'/g, '"')));//key: ["AK", "FL", "NY"]
I did something like this
var rules = {
//Data
"['AK','FL','NY']": {a: 278},
"['CA','LA','TX']": {a: 422},
BA: {a: 111},
BC: {a: 222},
//Function
getKey: function(key){
return Object.keys(this).find((val) => {
return val.replace(/(\[|\]|'|")/g,'')
.split(',')
.includes(key)
}
)
},
get: function(key){
return this[this.getKey(key)]
}
}
console.log(rules.get('AK')) //{a: 278}
console.log(rules.get('BA')) //{a: 111}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.