java后端和JS前端权限位运算

package com.zw.util;

/**
 * 权限数字的运算
 * @author andy.wang
 *
 */
public class Competence {

	/**
	 * 根据权限点得到权限的总和
	 * @param i
	 * @return
	 */
	public static Integer getProduct(Integer[] i){
		Integer x=0;
		if (i==null||i.length==0) {
			return x;
		}
		for (int j : i) {
			x=x+(int)Math.pow(2,j);
		}
		return x;
	}
	
	/**
	 * 添加一个权限点
	 * @param i
	 * @return
	 */
	public static Integer addProduct(Integer i,Integer y){
		return(i)|((int)Math.pow(2,y));
	}
	
	/**
	 * 移除一个权限点
	 * @param i
	 * @return
	 */
	public static Integer rmProduct(Integer i,Integer y){
		return(i)&~((int)Math.pow(2,y));
	}
	
	/**
	 * 合并两个权限值
	 * @param i
	 * @return
	 */
	public static Integer ergerProduct(Integer i,Integer y){
		return i|y;
	}
	
	/**
	 * 检查权限点是否在权限值中
	 * @param i
	 * @return
	 */
	public static boolean checkProduct(Integer i,Integer y){
		Integer x = (int)Math.pow(2,y);
		return x==(i&x);
	}
	
	public static void main(String[] args) {
		Integer[] ii = new Integer[]{1,2,4,6,8};
		Integer[] iii = new Integer[]{1,2,4,5};
		Integer comp = getProduct(ii);//计算出权限值
		Integer comp1 = getProduct(iii);//计算出权限值
		comp = ergerProduct(comp, comp1);//合并两个权限值 重复的权限合并也可以
		comp=addProduct(comp, 7);//添加一个额外的权限点
		comp=addProduct(comp, 7);//添加一个额外的权限点多次添加也没关系
		comp = rmProduct(comp, 5);//移除一个权限值
		comp = rmProduct(comp, 5);//移除一个权限值 多次移除也没关系
		System.out.println(checkProduct(comp, 1));//检查权限
		System.out.println(checkProduct(comp, 2));
		System.out.println(checkProduct(comp, 4));
		System.out.println(checkProduct(comp, 5));
		System.out.println(checkProduct(comp, 7));
		System.out.println(checkProduct(comp, 8));
		System.out.println(checkProduct(comp, 9));
	}
	
}
还有一个js版本的

//计算权限点总和
function getProduct(array) {
		var x = 0;
		if (array.length == 0) {
			return x;
		}
		for (var i=0;i





你可能感兴趣的:(java,JS)