Question

I am trying to refactor some code. All along the code base, I have code that stores user-related informations like this :

this.users[user][field] = data ;

Note that there could be an arbitrary number of subfields (including none), like this:

this.users[user][field][subfield1][subfield2] = data ;

Theses informations are retrieved like this :

var result = this.users[user][field] ;

In production, the actual data will be stored into Redis. To prepare for this, I would like to refactor those access into two functions, say function storeUserData(user, fields, data) and function retrieveUserData(user, field).

I can do it trivially if there is only one field. But how can I write those two functions to allow for an arbitrary number of subfields (ideally none as well) ?

Edit : the long-term goal is to blur the difference between redis keys and node.js arrays. That way I could for instance access a node subfield like this : 'users.user.id' and also have it in redis like this :users.user.*.id. Does that seem feasible ?

Était-ce utile?

La solution

You can pass the fields argument as an Array. Then in your read function do something like

function retrieveUserData(user, fields) {

// imagine fields is ['field', 'subfield1']

var fieldVariable = this.users[user] for (f = 0; f < fields.length; ++f) { fieldVariable = fieldVariable[fields[f]]; }

// in this line fieldVariable will point to this.users[user]['field']['subfield1']

return fieldVariable; }

Hope it helps!

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top