[英]How can I use the binary system (1, 2, 4) as an algorithm?
Similar to chmod, I would like to use 1, 2, 4 as a way of notifications. 与chmod相似,我想使用1、2、4作为通知方式。
1 = Email
2 = SMS
4 = Push notifications
Is there function (preferably in javascript) that can input a number (above) and can return an object with: 是否有函数(最好是在javascript中)可以输入一个数字(上面)并且可以返回一个对象:
{
email: true,
sms: true,
push: false
}
I want the function to not be hard coded. 我希望函数不被硬编码。 I don't want a bunch of if statements that check for every combination there is. 我不想要一堆if语句来检查是否存在每种组合。 I want a "smart" way to do it. 我想要一种“智能”的方法。
How about something like this: 这样的事情怎么样:
var commsMode = {
email: 1,
sms: 2,
push: 4,
toObject: function(val){
var rt = {};
for (e in commsMode) {
rt[e] = (val & commsMode[e]) > 0;
}
return rt;
}
};
var obj = commsMode.toObject(3);
Working example here . 这里的工作示例 。
Extended example: 扩展示例:
var commsMode = {
email: 1,
sms: 2,
push: 4,
mode4: 8,
mode5: 16,
mode6: 32,
mode7: 64,
mode8: 128,
toObject: function(val){
var rt = {};
for (e in commsMode) {
rt[e] = (val & commsMode[e]) > 0;
}
return rt;
}
};
var obj = commsMode.toObject(233);
for (p in obj) {
alert(p + ': ' + obj[p])
}
Try something like this - sorry, this is Python, but the JavaScript translation should be very similar: 尝试类似的方法-抱歉,这是Python,但是JavaScript转换应该非常相似:
def notifications(mask):
return {
'email' : mask & 4 != 0,
'sms' : mask & 2 != 0,
'push' : mask & 1 != 0
}
notifications(0b111) # same as notifications(7), or notifications(email+sms+push)
=> {'push': True, 'sms': True, 'email': True}
In the above, we're saying that the notifications binary bit mask is 0b111
(or 7, if you prefer to use base-10), meaning that all three notifications are enabled. 在上面,我们说通知二进制位掩码是0b111
(或7,如果你更喜欢使用base-10),这意味着所有三个通知都被启用。 Similarly, if we had passed as bit mask 0b010
(or 2 in base-10), then the answer would have been: 同样,如果我们已经作为位掩码0b010
(或者基数为10中的2)传递,那么答案就是:
notifications(0b010) # same as notifications(2), or notifications(sms)
=> {'push': False, 'sms': True, 'email': False}
Solution with multiple parameters to send to function: 具有多个参数的解决方案发送到功能:
var states = {
'1': 'email',
'2': 'sms',
'4': 'push'
};
function getStates(){
var o = {};
for(var val in states){
o[states[val]] = false;
}
for(var i=0;i<arguments.length;i++){
var arg = arguments[i];
var state = states[arg];
if(state){
o[state] = true;
}
}
return o;
}
console.log(getStates()); // return {email: false, sms: false, push: false}
console.log(getStates(1,2)); // return {email: true, sms: true, push: false}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.