@lppx/nlearn 1.1.4 → 1.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,221 @@
1
+ "use strict";
2
+ /**
3
+ * TypeScript 类的静态成员与单例模式
4
+ * ===================================
5
+ * 介绍静态属性、静态方法和单例模式的实现
6
+ * 适用于 TypeScript 3.0+
7
+ */
8
+ // #region 示例1: 静态属性和方法
9
+ class MathUtils {
10
+ static add(a, b) {
11
+ return a + b;
12
+ }
13
+ static multiply(a, b) {
14
+ return a * b;
15
+ }
16
+ static circleArea(radius) {
17
+ return this.PI * radius ** 2;
18
+ }
19
+ static power(base, exponent) {
20
+ return Math.pow(base, exponent);
21
+ }
22
+ }
23
+ MathUtils.PI = 3.14159;
24
+ MathUtils.E = 2.71828;
25
+ function staticMembersDemo() {
26
+ // 直接通过类名访问静态成员,无需实例化
27
+ console.log('PI 的值:', MathUtils.PI);
28
+ console.log('E 的值:', MathUtils.E);
29
+ console.log('5 + 3 =', MathUtils.add(5, 3));
30
+ console.log('4 × 6 =', MathUtils.multiply(4, 6));
31
+ console.log('半径为 5 的圆面积:', MathUtils.circleArea(5).toFixed(2));
32
+ console.log('2 的 8 次方:', MathUtils.power(2, 8));
33
+ }
34
+ // #endregion
35
+ // #region 示例2: 静态属性计数器
36
+ class User {
37
+ constructor(username) {
38
+ this.username = username;
39
+ User.userCount++;
40
+ this.id = User.userCount;
41
+ User.users.push(this);
42
+ }
43
+ static getUserCount() {
44
+ return User.userCount;
45
+ }
46
+ static getAllUsers() {
47
+ return User.users;
48
+ }
49
+ static findUserById(id) {
50
+ return User.users.find(user => user.id === id);
51
+ }
52
+ displayInfo() {
53
+ console.log(`用户 ID: ${this.id}, 用户名: ${this.username}`);
54
+ }
55
+ }
56
+ User.userCount = 0;
57
+ User.users = [];
58
+ function staticCounterDemo() {
59
+ console.log('初始用户数:', User.getUserCount());
60
+ const user1 = new User('张三');
61
+ const user2 = new User('李四');
62
+ const user3 = new User('王五');
63
+ console.log('当前用户数:', User.getUserCount());
64
+ console.log('\n所有用户:');
65
+ User.getAllUsers().forEach(user => user.displayInfo());
66
+ console.log('\n查找 ID 为 2 的用户:');
67
+ const foundUser = User.findUserById(2);
68
+ foundUser?.displayInfo();
69
+ }
70
+ // #endregion
71
+ // #region 示例3: 单例模式 - 基础实现
72
+ class Database {
73
+ // 私有构造函数,防止外部实例化
74
+ constructor() {
75
+ this.connectionString = 'mongodb://localhost:27017/mydb';
76
+ console.log('数据库连接已创建');
77
+ }
78
+ static getInstance() {
79
+ if (!Database.instance) {
80
+ Database.instance = new Database();
81
+ }
82
+ return Database.instance;
83
+ }
84
+ query(sql) {
85
+ console.log(`执行查询: ${sql}`);
86
+ console.log(`连接字符串: ${this.connectionString}`);
87
+ }
88
+ }
89
+ function singletonBasicDemo() {
90
+ // const db = new Database(); // 错误:构造函数是私有的
91
+ const db1 = Database.getInstance();
92
+ db1.query('SELECT * FROM users');
93
+ console.log();
94
+ const db2 = Database.getInstance();
95
+ db2.query('SELECT * FROM products');
96
+ console.log();
97
+ console.log('db1 和 db2 是同一个实例:', db1 === db2);
98
+ }
99
+ // #endregion
100
+ // #region 示例4: 单例模式 - 配置管理器
101
+ class ConfigManager {
102
+ constructor() {
103
+ this.config = new Map();
104
+ this.loadDefaultConfig();
105
+ }
106
+ static getInstance() {
107
+ if (!ConfigManager.instance) {
108
+ ConfigManager.instance = new ConfigManager();
109
+ }
110
+ return ConfigManager.instance;
111
+ }
112
+ loadDefaultConfig() {
113
+ this.config.set('appName', 'MyApp');
114
+ this.config.set('version', '1.0.0');
115
+ this.config.set('debug', false);
116
+ console.log('默认配置已加载');
117
+ }
118
+ get(key) {
119
+ return this.config.get(key);
120
+ }
121
+ set(key, value) {
122
+ this.config.set(key, value);
123
+ console.log(`配置已更新: ${key} = ${value}`);
124
+ }
125
+ getAll() {
126
+ return Object.fromEntries(this.config);
127
+ }
128
+ }
129
+ function configManagerDemo() {
130
+ const config1 = ConfigManager.getInstance();
131
+ console.log('应用名称:', config1.get('appName'));
132
+ console.log('版本:', config1.get('version'));
133
+ console.log();
134
+ config1.set('debug', true);
135
+ config1.set('port', 3000);
136
+ console.log();
137
+ const config2 = ConfigManager.getInstance();
138
+ console.log('所有配置:', config2.getAll());
139
+ console.log('config1 和 config2 是同一个实例:', config1 === config2);
140
+ }
141
+ // #endregion
142
+ // #region 示例5: 静态工厂方法
143
+ class Logger {
144
+ constructor(level, prefix) {
145
+ this.level = level;
146
+ this.prefix = prefix;
147
+ }
148
+ static createConsoleLogger() {
149
+ return new Logger('INFO', '[Console]');
150
+ }
151
+ static createFileLogger() {
152
+ return new Logger('DEBUG', '[File]');
153
+ }
154
+ static createErrorLogger() {
155
+ return new Logger('ERROR', '[Error]');
156
+ }
157
+ log(message) {
158
+ console.log(`${this.prefix} [${this.level}] ${message}`);
159
+ }
160
+ }
161
+ class DateFormatter {
162
+ constructor(formatPattern) {
163
+ this.formatPattern = formatPattern;
164
+ }
165
+ static createShortFormat() {
166
+ return new DateFormatter('YYYY-MM-DD');
167
+ }
168
+ static createLongFormat() {
169
+ return new DateFormatter('YYYY-MM-DD HH:mm:ss');
170
+ }
171
+ format(date) {
172
+ const year = date.getFullYear();
173
+ const month = String(date.getMonth() + 1).padStart(2, '0');
174
+ const day = String(date.getDate()).padStart(2, '0');
175
+ if (this.formatPattern === 'YYYY-MM-DD') {
176
+ return `${year}-${month}-${day}`;
177
+ }
178
+ else {
179
+ const hours = String(date.getHours()).padStart(2, '0');
180
+ const minutes = String(date.getMinutes()).padStart(2, '0');
181
+ const seconds = String(date.getSeconds()).padStart(2, '0');
182
+ return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
183
+ }
184
+ }
185
+ }
186
+ function staticFactoryDemo() {
187
+ const consoleLogger = Logger.createConsoleLogger();
188
+ const fileLogger = Logger.createFileLogger();
189
+ const errorLogger = Logger.createErrorLogger();
190
+ consoleLogger.log('这是一条控制台日志');
191
+ fileLogger.log('这是一条文件日志');
192
+ errorLogger.log('这是一条错误日志');
193
+ console.log();
194
+ const now = new Date();
195
+ const shortFormatter = DateFormatter.createShortFormat();
196
+ const longFormatter = DateFormatter.createLongFormat();
197
+ console.log('短格式:', shortFormatter.format(now));
198
+ console.log('长格式:', longFormatter.format(now));
199
+ }
200
+ // #endregion
201
+ if (require.main === module) {
202
+ const demos = [
203
+ staticMembersDemo,
204
+ staticCounterDemo,
205
+ singletonBasicDemo,
206
+ configManagerDemo,
207
+ staticFactoryDemo
208
+ ];
209
+ const index = parseInt(process.argv[2]) || 0;
210
+ if (index > 0 && index <= demos.length) {
211
+ console.log(`\n=== 运行示例 ${index} ===\n`);
212
+ demos[index - 1]();
213
+ }
214
+ else {
215
+ console.log('=== 运行所有示例 ===\n');
216
+ demos.forEach((demo, i) => {
217
+ console.log(`\n--- 示例 ${i + 1}: ${demo.name} ---\n`);
218
+ demo();
219
+ });
220
+ }
221
+ }
@@ -0,0 +1,163 @@
1
+ "use strict";
2
+ /**
3
+ * TypeScript 类与接口
4
+ * ====================
5
+ * 介绍接口定义、类实现接口、接口继承
6
+ * 适用于 TypeScript 3.0+
7
+ */
8
+ class Document {
9
+ constructor(content) {
10
+ this.content = content;
11
+ }
12
+ print() {
13
+ console.log('打印文档:');
14
+ console.log(this.content);
15
+ }
16
+ }
17
+ class Image {
18
+ constructor(url, width, height) {
19
+ this.url = url;
20
+ this.width = width;
21
+ this.height = height;
22
+ }
23
+ print() {
24
+ console.log(`打印图片: ${this.url}`);
25
+ console.log(`尺寸: ${this.width}x${this.height}`);
26
+ }
27
+ }
28
+ function singleInterfaceDemo() {
29
+ const doc = new Document('这是一份重要文档');
30
+ doc.print();
31
+ console.log();
32
+ const img = new Image('photo.jpg', 1920, 1080);
33
+ img.print();
34
+ }
35
+ class Duck {
36
+ constructor(name) {
37
+ this.name = name;
38
+ }
39
+ fly() {
40
+ console.log(`${this.name} 在飞翔`);
41
+ }
42
+ swim() {
43
+ console.log(`${this.name} 在游泳`);
44
+ }
45
+ }
46
+ class Penguin {
47
+ constructor(name) {
48
+ this.name = name;
49
+ }
50
+ swim() {
51
+ console.log(`${this.name} 在游泳`);
52
+ }
53
+ }
54
+ function multipleInterfacesDemo() {
55
+ const duck = new Duck('唐老鸭');
56
+ duck.fly();
57
+ duck.swim();
58
+ console.log();
59
+ const penguin = new Penguin('企鹅');
60
+ penguin.swim();
61
+ }
62
+ class Student {
63
+ constructor(name, age, email, studentId) {
64
+ this.name = name;
65
+ this.age = age;
66
+ this.email = email;
67
+ this.studentId = studentId;
68
+ }
69
+ greet() {
70
+ console.log(`你好,我是学生 ${this.name}`);
71
+ }
72
+ displayInfo() {
73
+ console.log(`学生: ${this.name}`);
74
+ console.log(`年龄: ${this.age}`);
75
+ console.log(`邮箱: ${this.email}`);
76
+ console.log(`学号: ${this.studentId}`);
77
+ }
78
+ }
79
+ function interfaceInheritanceDemo() {
80
+ const student = new Student('张三', 20, 'zhangsan@example.com', 'S2024001');
81
+ student.displayInfo();
82
+ }
83
+ class BasicCalculator {
84
+ add(a, b) {
85
+ return a + b;
86
+ }
87
+ subtract(a, b) {
88
+ return a - b;
89
+ }
90
+ multiply(a, b) {
91
+ return a * b;
92
+ }
93
+ divide(a, b) {
94
+ if (b === 0) {
95
+ throw new Error('除数不能为零');
96
+ }
97
+ return a / b;
98
+ }
99
+ }
100
+ function methodSignatureDemo() {
101
+ const calc = new BasicCalculator();
102
+ console.log('10 + 5 =', calc.add(10, 5));
103
+ console.log('10 - 5 =', calc.subtract(10, 5));
104
+ console.log('10 × 5 =', calc.multiply(10, 5));
105
+ console.log('10 ÷ 5 =', calc.divide(10, 5));
106
+ }
107
+ class Version {
108
+ constructor(major, minor, patch) {
109
+ this.major = major;
110
+ this.minor = minor;
111
+ this.patch = patch;
112
+ }
113
+ compareTo(other) {
114
+ if (this.major !== other.major) {
115
+ return this.major - other.major;
116
+ }
117
+ if (this.minor !== other.minor) {
118
+ return this.minor - other.minor;
119
+ }
120
+ return this.patch - other.patch;
121
+ }
122
+ toString() {
123
+ return `${this.major}.${this.minor}.${this.patch}`;
124
+ }
125
+ }
126
+ function sortVersions(versions) {
127
+ return versions.sort((a, b) => a.compareTo(b));
128
+ }
129
+ function genericInterfaceDemo() {
130
+ const versions = [
131
+ new Version(2, 1, 0),
132
+ new Version(1, 5, 3),
133
+ new Version(2, 0, 1),
134
+ new Version(1, 5, 10)
135
+ ];
136
+ console.log('排序前:');
137
+ versions.forEach(v => console.log(v.toString()));
138
+ const sorted = sortVersions(versions);
139
+ console.log('\n排序后:');
140
+ sorted.forEach(v => console.log(v.toString()));
141
+ }
142
+ // #endregion
143
+ if (require.main === module) {
144
+ const demos = [
145
+ singleInterfaceDemo,
146
+ multipleInterfacesDemo,
147
+ interfaceInheritanceDemo,
148
+ methodSignatureDemo,
149
+ genericInterfaceDemo
150
+ ];
151
+ const index = parseInt(process.argv[2]) || 0;
152
+ if (index > 0 && index <= demos.length) {
153
+ console.log(`\n=== 运行示例 ${index} ===\n`);
154
+ demos[index - 1]();
155
+ }
156
+ else {
157
+ console.log('=== 运行所有示例 ===\n');
158
+ demos.forEach((demo, i) => {
159
+ console.log(`\n--- 示例 ${i + 1}: ${demo.name} ---\n`);
160
+ demo();
161
+ });
162
+ }
163
+ }
@@ -0,0 +1,168 @@
1
+ "use strict";
2
+ /**
3
+ * Fuse.js 基础概念
4
+ * ================
5
+ * Fuse.js 是一个轻量级的模糊搜索库,零依赖
6
+ * 适用于客户端对小到中等规模数据集进行模糊搜索
7
+ *
8
+ * 官方文档: https://www.fusejs.io/
9
+ * 适用版本: fuse.js 7.x
10
+ */
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const fuse_js_1 = __importDefault(require("fuse.js"));
16
+ // #region 示例1: 简单字符串数组搜索
17
+ function 搜索字符串数组() {
18
+ console.log('\n=== 示例1: 简单字符串数组搜索 ===');
19
+ // 准备数据
20
+ const fruits = ['Apple', 'Banana', 'Orange', 'Pineapple', 'Grape', 'Watermelon'];
21
+ // 创建 Fuse 实例
22
+ const fuse = new fuse_js_1.default(fruits, {
23
+ includeScore: true
24
+ });
25
+ // 执行搜索
26
+ const result = fuse.search('aple'); // 故意拼错,测试模糊搜索
27
+ console.log('搜索 "aple" 的结果:');
28
+ result.forEach(item => {
29
+ console.log(` - ${item.item} (匹配度: ${item.score?.toFixed(3)})`);
30
+ });
31
+ }
32
+ // #endregion
33
+ // #region 示例2: 搜索对象数组
34
+ function 搜索对象数组() {
35
+ console.log('\n=== 示例2: 搜索对象数组 ===');
36
+ // 准备书籍数据
37
+ const books = [
38
+ { title: 'JavaScript 高级程序设计', author: 'Nicholas C. Zakas' },
39
+ { title: 'TypeScript 编程', author: 'Boris Cherny' },
40
+ { title: 'Node.js 设计模式', author: 'Mario Casciaro' },
41
+ { title: 'Vue.js 实战', author: '梁灏' },
42
+ { title: 'React 进阶之路', author: '徐超' }
43
+ ];
44
+ // 配置搜索的键
45
+ const fuse = new fuse_js_1.default(books, {
46
+ keys: ['title', 'author']
47
+ });
48
+ // 搜索标题或作者包含 "script" 的书籍
49
+ const result = fuse.search('script');
50
+ console.log('搜索 "script" 的结果:');
51
+ result.forEach(item => {
52
+ console.log(` - ${item.item.title} by ${item.item.author}`);
53
+ console.log(` 匹配度: ${item.score?.toFixed(3)}`);
54
+ });
55
+ }
56
+ // #endregion
57
+ // #region 示例3: 基础配置选项
58
+ function 基础配置选项() {
59
+ console.log('\n=== 示例3: 基础配置选项 ===');
60
+ const languages = [
61
+ 'JavaScript',
62
+ 'TypeScript',
63
+ 'Python',
64
+ 'Java',
65
+ 'C++',
66
+ 'Ruby'
67
+ ];
68
+ // 配置 Fuse 选项
69
+ const fuse = new fuse_js_1.default(languages, {
70
+ threshold: 0.3, // 匹配阈值,0.0 完全匹配,1.0 匹配任何内容
71
+ distance: 100, // 搜索距离
72
+ includeScore: true, // 包含匹配分数
73
+ minMatchCharLength: 2 // 最小匹配字符长度
74
+ });
75
+ console.log('配置说明:');
76
+ console.log(' - threshold: 0.3 (较严格的匹配)');
77
+ console.log(' - distance: 100');
78
+ console.log(' - includeScore: true');
79
+ console.log(' - minMatchCharLength: 2\n');
80
+ const result = fuse.search('java');
81
+ console.log('搜索 "java" 的结果:');
82
+ result.forEach(item => {
83
+ console.log(` - ${item.item} (分数: ${item.score?.toFixed(3)})`);
84
+ });
85
+ }
86
+ // #endregion
87
+ // #region 示例4: 嵌套对象搜索
88
+ function 嵌套对象搜索() {
89
+ console.log('\n=== 示例4: 嵌套对象搜索 ===');
90
+ // 准备嵌套结构的数据
91
+ const users = [
92
+ {
93
+ name: '张三',
94
+ profile: {
95
+ email: 'zhangsan@example.com',
96
+ city: '北京'
97
+ }
98
+ },
99
+ {
100
+ name: '李四',
101
+ profile: {
102
+ email: 'lisi@example.com',
103
+ city: '上海'
104
+ }
105
+ },
106
+ {
107
+ name: '王五',
108
+ profile: {
109
+ email: 'wangwu@example.com',
110
+ city: '深圳'
111
+ }
112
+ }
113
+ ];
114
+ // 使用点号访问嵌套属性
115
+ const fuse = new fuse_js_1.default(users, {
116
+ keys: ['name', 'profile.email', 'profile.city']
117
+ });
118
+ const result = fuse.search('上海');
119
+ console.log('搜索 "上海" 的结果:');
120
+ result.forEach(item => {
121
+ console.log(` - ${item.item.name}`);
122
+ console.log(` 邮箱: ${item.item.profile.email}`);
123
+ console.log(` 城市: ${item.item.profile.city}`);
124
+ });
125
+ }
126
+ // #endregion
127
+ // #region 示例5: 获取所有结果与限制结果数量
128
+ function 结果数量控制() {
129
+ console.log('\n=== 示例5: 结果数量控制 ===');
130
+ const countries = [
131
+ 'China', 'Canada', 'Chile', 'Colombia', 'Croatia',
132
+ 'Cuba', 'Cyprus', 'Czech Republic', 'Cambodia', 'Cameroon'
133
+ ];
134
+ const fuse = new fuse_js_1.default(countries);
135
+ // 搜索以 C 开头的国家
136
+ const allResults = fuse.search('c');
137
+ console.log(`搜索 "c" 找到 ${allResults.length} 个结果:`);
138
+ allResults.slice(0, 5).forEach((item, index) => {
139
+ console.log(` ${index + 1}. ${item.item}`);
140
+ });
141
+ if (allResults.length > 5) {
142
+ console.log(` ... 还有 ${allResults.length - 5} 个结果`);
143
+ }
144
+ }
145
+ // #endregion
146
+ // #region 主程序入口
147
+ if (require.main === module) {
148
+ const args = process.argv.slice(2);
149
+ const exampleNumber = args[0] ? parseInt(args[0]) : 0;
150
+ const examples = [
151
+ 搜索字符串数组,
152
+ 搜索对象数组,
153
+ 基础配置选项,
154
+ 嵌套对象搜索,
155
+ 结果数量控制
156
+ ];
157
+ if (exampleNumber > 0 && exampleNumber <= examples.length) {
158
+ console.log(`\n运行示例 ${exampleNumber}:`);
159
+ examples[exampleNumber - 1]();
160
+ }
161
+ else {
162
+ console.log('Fuse.js 基础概念示例\n');
163
+ console.log('运行所有示例...\n');
164
+ examples.forEach(example => example());
165
+ console.log('\n\n提示: 使用 ts-node src/demo/fuse/01-基础概念.ts [1-5] 运行指定示例');
166
+ }
167
+ }
168
+ // #endregion