Files
sql-like-filter/README.md
2025-12-30 01:00:53 +08:00

75 lines
1.8 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# JS Filter
轻量、易读、可解析、可执行的类 SQL 过滤语法,用于 JavaScript 数组过滤。
## 语法特性
- **WHERE**: 条件过滤
- **ORDER BY**: 排序
- **LIMIT**: 限制结果数量
- **操作符**: `=`, `!=`, `>`, `<`, `>=`, `<=`, `IN`, `CONTAINS`, `LIKE`
- **逻辑**: `AND`, `OR`
## 语法示例
```javascript
// 基础过滤
filter(users, "WHERE metadata.type = 'user'");
// 多条件
filter(users, "WHERE metadata.tags CONTAINS 'premium' AND metadata.region = 'beijing'");
// 排序
filter(users, "WHERE metadata.type = 'user' ORDER BY metadata.created_at DESC");
// 限制数量
filter(users, "WHERE metadata.type = 'user' ORDER BY metadata.created_at DESC LIMIT 10");
// IN 操作
filter(users, "WHERE metadata.region IN ['beijing', 'shanghai']");
// LIKE 操作 (支持 % 匹配任意字符_ 匹配单个字符)
filter(products, "WHERE name LIKE '%Apple%'");
filter(products, "WHERE name LIKE 'Apple%'");
filter(products, "WHERE name LIKE '%Phone'");
```
## 使用方法
```javascript
import { filter } from '@kevisual/js-filter';
const users = [
{
metadata: {
tags: ['premium', 'active'],
type: 'user',
region: 'beijing',
created_at: '2024-03-15T10:00:00Z',
},
},
{
metadata: {
tags: ['free'],
type: 'admin',
region: 'shanghai',
created_at: '2024-01-10T09:00:00Z',
},
},
{
metadata: {
tags: ['enterprise', 'premium'],
type: 'user',
region: 'guangzhou',
created_at: '2024-04-05T12:00:00Z',
},
},
];
// 查找 premium 用户
const premiumUsers = filter(users, "WHERE metadata.tags CONTAINS 'premium'");
// 查找北京的用户,按创建时间倒序
const beijingUsers = filter(users, "WHERE metadata.region = 'beijing' ORDER BY metadata.created_at DESC");
```