npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@ismartify/mapstore

v1.0.7

Published

[![npm version](https://badge.fury.io/js/%40ismartify%2Fmapstore.svg)](https://badge.fury.io/js/%40ismartify%2Fmapstore) [![License: ISC](https://img.shields.io/badge/License-ISC-blue.svg)](https://opensource.org/licenses/ISC)

Readme

ISmartify MapStore

npm version License: ISC

一个基于 Map 的轻量级存储工具库,提供链式操作、函数混入、执行器模式等功能的简洁易用接口。特别设计的 exec 方法支持在链式调用中无缝执行复杂业务逻辑,结合自动 this 绑定,提供优雅的函数式编程体验。

✨ 特性

  • 🏃 执行器模式exec 方法支持在链式调用中执行复杂逻辑,自动绑定 this
  • 🔗 链式操作:支持流畅的链式调用,结合 exec 实现复杂数据流
  • 🔧 函数混入:支持动态添加和调用自定义函数
  • 🎯 多执行模式:提供 callexec 等多种函数执行方式
  • 🐛 调试友好:内置 tap 方法支持正则过滤和表格输出
  • 🛡️ 类型安全:完整的 TypeScript 支持
  • 📦 零依赖:无外部依赖,轻量级设计

📦 安装

npm install @ismartify/mapstore
# 或
pnpm add @ismartify/mapstore
# 或
yarn add @ismartify/mapstore

🚀 快速开始

import { ISmartifyMapStore } from '@ismartify/mapstore';

// 创建存储实例
const store = new ISmartifyMapStore();

// 基础操作
store
  .set('user', { name: 'John', age: 30 })
  .set('config', { theme: 'dark' })
  .set('count', 0);

// 获取数据
const user = store.get('user');
const theme = store.get('config.theme', 'light'); // 带默认值

// 检查和删除
if (store.has('count')) {
  store.delete('count');
}

// 调试输出
store.tap(); // 输出所有数据到控制台表格

📖 API 文档

基础方法

set(key: string, value: any): this

设置键值对,支持链式调用。

store.set('name', 'John').set('age', 30);

get(key: string, defaultValue?: any): any

获取值,支持默认值。

const name = store.get('name');
const age = store.get('age', 0); // 如果不存在返回 0

has(key: string): boolean

检查键是否存在。

if (store.has('user')) {
  console.log('用户存在');
}

delete(key: string): this

删除键值对,支持链式调用。

store.delete('temp').delete('cache');

clear(): this

清空所有数据,支持链式调用。

store.clear();

pick(...keys: string[]): any[]

提取多个键的值。

const [name, age] = store.pick('name', 'age');

raw(): Map<string, any>

获取原始 Map 对象。

const rawMap = store.raw();

函数混入

mixin(name: string, fn: Function): this

添加自定义函数到存储中。

store.mixin('increment', (self, key, step = 1) => {
  const current = self.get(key, 0);
  return self.set(key, current + step);
});

call<T>(name: string, ...args: any[]): ReturnType<T>

调用混入的函数。

store.set('counter', 5);
store.call('increment', 'counter', 2); // counter 变为 7

执行器模式

exec<T>(callback: (self: this, ...args: any[]) => any, ...args: any[]): ReturnType<T>

执行回调函数,自动传入当前实例作为第一个参数,支持在链式调用中执行复杂逻辑。

设计初衷

  • 在方法链中执行复杂逻辑,同时保持链式调用的流畅性
  • 自动绑定当前实例,避免手动传递 this
  • 支持箭头函数,提供更好的函数式编程体验

核心特性

  • 自动 this 绑定:回调函数的第一个参数自动接收当前实例
  • 类型安全:支持泛型,保持完整的类型推断
  • 链式友好:可以在任何链式调用中插入复杂逻辑
// 基础用法
const result = store.exec((self) => {
  const count = self.get<number>('count', 0);
  return self.set('count', count + 1);
});

// 带参数的用法
store.exec((self, multiplier, offset) => {
  const value = self.get<number>('base', 0);
  return self.set('result', value * multiplier + offset);
}, 2, 10);

// 在链式调用中的复杂计算
const summary = store
  .set('items', [{price: 10}, {price: 20}, {price: 30}])
  .exec((self) => {
    const items = self.get<any[]>('items') || [];
    const total = items.reduce((sum, item) => sum + item.price, 0);
    const avg = total / items.length;
    self.set('total', total).set('average', avg);
    return { count: items.length, total, avg };
  });

使用场景

  1. 链式调用中的复杂计算
const processed = store
  .set('rawData', [1, 2, 3, 4, 5])
  .exec((self) => {
    const data = self.get<number[]>('rawData') || [];
    const filtered = data.filter(n => n > 2);
    const sum = filtered.reduce((a, b) => a + b, 0);
    return self.set('processed', { filtered, sum });
  });
  1. 条件逻辑执行
store
  .set('user', { role: 'admin', permissions: [] })
  .exec((self) => {
    const user = self.get('user');
    if (user && user.role === 'admin') {
      self.set('permissions', ['read', 'write', 'delete']);
    }
  });
  1. 数据验证和转换
const isValid = store
  .set('input', 'user input')
  .exec((self) => {
    const input = self.get<string>('input');
    const isValid = input && input.length >= 3;
    
    if (isValid) {
      self.set('normalized', input.trim().toLowerCase());
    }
    
    return isValid;
  });

mixin/call 的区别

  • mixin/call:适合重复使用的命名函数
  • exec:适合一次性执行的复杂逻辑
// mixin/call 适合重复使用的逻辑
store.mixin('validateEmail', (self, email) => {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
});

// exec 适合临时复杂逻辑
store.exec((self) => {
  const user = self.get('user');
  const email = user?.email;
  const isValid = self.call('validateEmail', email);
  
  if (isValid) {
    self.set('user.valid', true);
  }
  
  return isValid;
});

调试方法

tap(rule?: string | RegExp): this

调试输出,支持正则过滤。

// 输出所有数据
store.tap();

// 只输出以 'user' 开头的键
store.tap('^user');

// 使用正则表达式
store.tap(/config|setting/);

🎯 使用场景

1. 配置管理

const config = new ISmartifyMapStore();

config
  .set('api.baseUrl', 'https://api.example.com')
  .set('api.timeout', 5000)
  .set('ui.theme', 'dark')
  .set('ui.language', 'zh-CN');

// 获取配置
const apiUrl = config.get('api.baseUrl');
const timeout = config.get('api.timeout', 3000);

2. 状态管理

const state = new ISmartifyMapStore();

// 添加状态更新函数
state.mixin('updateUser', (self, userData) => {
  return self.set('user', { ...self.get('user', {}), ...userData });
});

state.mixin('incrementCounter', (self, key = 'counter') => {
  return self.set(key, self.get(key, 0) + 1);
});

// 使用
state.call('updateUser', { name: 'Alice', age: 25 });
state.call('incrementCounter');

3. 缓存系统

const cache = new ISmartifyMapStore();

// 添加缓存逻辑
cache.mixin('setWithTTL', (self, key, value, ttl = 60000) => {
  const expiry = Date.now() + ttl;
  return self.set(key, { value, expiry });
});

cache.mixin('getValid', (self, key) => {
  const item = self.get(key);
  if (!item) return null;
  
  if (Date.now() > item.expiry) {
    self.delete(key);
    return null;
  }
  
  return item.value;
});

// 使用缓存
cache.call('setWithTTL', 'user:123', { name: 'John' }, 30000);
const user = cache.call('getValid', 'user:123');

5. 复杂业务逻辑处理

const workflow = new ISmartifyMapStore();

// 模拟用户注册流程
workflow
  .set('userInput', { email: '[email protected]', password: '123456' })
  .exec((self) => {
    // 验证输入
    const input = self.get('userInput');
    const isValid = input.email && input.password && input.password.length >= 6;
    
    if (!isValid) {
      throw new Error('Invalid input');
    }
    
    return self.set('validation', { passed: true, timestamp: Date.now() });
  })
  .exec((self) => {
    // 模拟数据库操作
    const user = self.get('userInput');
    const userId = Math.random().toString(36).substr(2, 9);
    
    return self.set('userRecord', {
      id: userId,
      email: user.email,
      createdAt: new Date().toISOString()
    });
  })
  .exec((self) => {
    // 发送欢迎邮件(模拟)
    const user = self.get('userRecord');
    console.log(`Welcome email sent to ${user.email}`);
    
    return self.set('emailSent', true);
  })
  .tap('^(user|validation|email)'); // 调试输出相关数据

🔧 高级用法

链式操作组合

const result = new ISmartifyMapStore()
  .set('data', [])
  .mixin('addItem', (self, item) => {
    const items = self.get('data', []);
    return self.set('data', [...items, item]);
  })
  .call('addItem', { id: 1, name: 'Item 1' })
  .call('addItem', { id: 2, name: 'Item 2' })
  .tap('^data') // 调试输出
  .get('data');

函数式编程风格

const store = new ISmartifyMapStore();

// 函数式数据处理 - 使用 exec 进行复杂的数据转换
store.exec((self) => {
  const numbers = [1, 2, 3, 4, 5];
  const sum = numbers.reduce((a, b) => a + b, 0);
  const avg = sum / numbers.length;
  
  return self
    .set('numbers', numbers)
    .set('sum', sum)
    .set('average', avg);
});

// 链式调用结合 exec 的数据流处理
const result = new ISmartifyMapStore()
  .set('rawData', [
    { id: 1, value: 10, active: true },
    { id: 2, value: 20, active: false },
    { id: 3, value: 30, active: true }
  ])
  .exec((self) => {
    const data = self.get<any[]>('rawData') || [];
    const processed = data
      .filter(item => item.active)
      .map(item => ({ ...item, value: item.value * 1.1 }))
      .sort((a, b) => b.value - a.value);
    
    const stats = {
      total: processed.length,
      sum: processed.reduce((sum, item) => sum + item.value, 0),
      avg: processed.reduce((sum, item) => sum + item.value, 0) / processed.length
    };
    
    return self
      .set('processed', processed)
      .set('stats', stats);
  })
  .exec((self) => {
    const stats = self.get('stats');
    console.log('处理完成:', stats);
    return stats;
  });

📝 注意事项

  1. 命名空间:构造函数会自动设置 __namespace 键,避免手动修改
  2. 函数混入:混入的函数以 @. 前缀存储,避免与普通数据冲突
  3. 类型安全:虽然内部使用 any,但建议在使用时进行类型断言
  4. 调试输出tap 方法在生产环境中可能影响性能,建议条件性使用

🔧 开发

# 安装依赖
pnpm install

# 运行测试
pnpm test

# 监听模式运行测试(开发时推荐)
pnpm run test:watch

# 运行测试覆盖率
pnpm run test:coverage

# 运行测试UI界面
pnpm run test:ui

# 构建项目
pnpm build

# 发布到 npm
pnpm run npm:publish

🤖 LLM 支持

本项目提供专门为大型语言模型优化的文档:

📄 llms.txt - 包含丰富的 TypeScript 代码示例和最佳实践

该文档包含:

  • 完整的 API 使用示例
  • 类型安全操作演示
  • 业务逻辑实现案例
  • 函数式编程模式展示

🤝 贡献

欢迎提交 Issue 和 Pull Request!

📞 联系我们

📄 许可证

ISC License