简体   繁体   中英

Ways to simplify an array of objects that is repeated several times

I wonder if I can simplify and use less lines of code for this purpose:

I have a class called "worker", and that class has a method that reads the properties (name, age, etc...) from a series of simple arrays.

Until there, everything is fine. Now, one of the properties that I want to add is a boolean value that makes reference to which months of the year the worker is active. For the moment, I have solved it like this:

var months_worker_1 = [{"jan":true},{"feb":true},{"mar":true},{"apr":false}] //and so on

And then, my property reads months_worker_1 , but I have one array like that for each worker. I wonder if there is a way to do this that requires less lines of code, like for example, create a "master" array with all the months of the year, and in the array for each worker, specify just the months they are working. Those months become "true", and the rest of months become "false" automatically without specifying so... I have been scratching my head for some time, and for the moment only my current system is working fine, but I am guessing that there must be a simpler way...

Thanks very much!

Edit: I clarify, there is no "big picture". I am just doing some exercises trying to learn javascript and this one woke my interest, because the solution I thought seems too complicated (repeating same array many times). There is no specific goal I need to achieve, I am just learning ways to do this.

A really nice trick that I use sometimes is to use a binary number to keep track of a fixed amount of flags, and convert it to a decimal for easier storage / URL embedding / etc. Let's assume Mark, a user, is active all months of the year. Considering a binary number, in which 1 means "active" and 0 inactive, Mark's flag would be:

111111111111 (twelve months)

if Mark would only be active during january, february and december, his flag value would be:

11000000001

Checking if Mark is active during a specific months is as simple as checking if the character that corresponds to that month's index in Mark's flag is 1 or 0 .

This technique has helped me in the past to send values for a large number of flags via URLs, while also keeping the URL reasonably short. Of course, you probably don't need this, but it's a nice thing to know:

Converting from binary to decimal is easy in JS:

parseInt(11000000001, 2).toString(10); // returns 1537

And the reverse:

parseInt((1537).toString(2)); // returns 11000000001

Edit

You could just as easily use an array made out of the month numbers:

var months_worker_1 = [1, 2, 3]; // this would mean that the user is active during january, february and march

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM