无法创建访问功能的JavaScript算法

时间:2019-09-25 19:21:36

标签: javascript algorithm

我的应用程序中有一些选项卡,例如报告,任务等... 用户还具有不同的权限,例如report.add,tasks.delete。 我需要创建函数来检查允许用户执行的操作。

// for example array with all current user permissions
// this permissions mean user is allowed to do everything with tasks
// add and edit reports, but not allowed to to delete it

const permissions = ['reports.add', 'reports.edit', 'tasks'];

const isAllowed = (condition) => {
   return permissions.some((permission) => {
            // here is problem, I can't create algorithm
       });
};


// When user clicks delete report button 
// I expect to use this function like this 

if (isAllowed('reports.delete')) {
    deleteReport()
}

2 个答案:

答案 0 :(得分:3)

如果permissionscondition开头,则可以在permission中进行搜索。

const
    permissions = ['reports.add', 'reports.edit', 'tasks'],
    isAllowed = condition => permissions.some(permission => condition.startsWith(permission));

console.log(isAllowed('reports.add')); //  true
console.log(isAllowed('tasks.edit'));  //  true
console.log(isAllowed('tasks'));       //  true
console.log(isAllowed('task'));        // false

答案 1 :(得分:1)

您可以只创建一个普通函数并避免在另一个函数内部使用匿名函数...

function isAllowed(permission) {
    return condition; //or some if-else
}