首页 > 解决方案 > 无法为访问函数创建 JavaScript 算法

问题描述

我的应用程序中有一些选项卡,如报告、任务等......用户也有不同的权限,如报告.添加、任务.删除。我需要创建函数来检查允许用户做什么。

// 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()
}

标签: javascriptalgorithm

解决方案


如果以. permissions_conditionpermission

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


推荐阅读