[英]JS. Replace nested loop to standard Array API
I had a case with comparing two arrays to getting user access to page:我有一个比较两个数组来让用户访问页面的案例:
let permitted = false;
const { authorities } = route.data;
const { roles } = user;
for (const role of roles) {
for (const authority of authorities) {
if (role.systemName === authority) {
permitted = true;
break;
}
}
}
User has an array of roles
and each role
has field systemName
is the value of an enum UserType
.用户有一个roles
数组,每个role
都有字段systemName
是枚举UserType
的值。
authorities
is array of UserType
values directly. authorities
是直接的UserType
值数组。
export enum UserType {
User = 'USER_ROLE',
Admin = 'ADMIN_ROLE',
}
How to refactor this nested loops with standard array API like some(...)
, indexOf(...)
of JavaScript?如何使用 JavaScript 的some(...)
、 indexOf(...)
等标准数组 API 重构此嵌套循环?
While you can do it with a nested .some
( O(n ^ 2)
), it would be more efficient to make a Set of one of the collections first, then use .some
on the other ( O(n)
):虽然您可以使用嵌套的.some
( O(n ^ 2)
) 来实现,但先制作一组集合中的一个集合,然后在另一个.some
上使用.some
( O(n)
) 会更有效:
const { authorities } = route.data;
const { roles } = user;
const systemNames = new Set(roles.map(({ systemName }) => systemName));
const permitted = authorities.some(
authority => systemNames.has(authority)
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.