JSPM

@viettv/universal-utils

2.0.0
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 6
  • Score
    100M100P100Q61120F
  • License MIT

A comprehensive utility library for file operations, HTTP requests, data processing, and more

Package Exports

  • @viettv/universal-utils
  • @viettv/universal-utils/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@viettv/universal-utils) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

@viettv/universal-utils

Thư viện tiện ích toàn diện cho các thao tác với file, HTTP requests, xử lý dữ liệu và nhiều hơn nữa.

Cài đặt

npm install @viettv/universal-utils

Sử dụng

Cách 1: Import toàn bộ thư viện

const utils = require('@viettv/universal-utils');

// Sử dụng các hàm
const files = await utils.getChildFileOrFolder('./mydir');
const data = await utils.readJsonFile('./data.json');
utils.notify('Success!').success();

Cách 2: Import riêng các Helper modules

// Array Helper
const arrayHelper = require('@viettv/universal-utils/array');
const unique = arrayHelper.unique([1, 2, 2, 3, 4, 4, 5]);
const chunks = arrayHelper.chunk([1, 2, 3, 4, 5, 6, 7], 3);

// Number Helper
const numberHelper = require('@viettv/universal-utils/number');
const sum = numberHelper.sum([1, 2, 3, 4, 5]);
const formatted = numberHelper.formatCurrency(1234.56);

// String Helper
const stringHelper = require('@viettv/universal-utils/string');
const slug = stringHelper.slugify('Hello World');
const camelCase = stringHelper.toCamelCase('hello world');

// Object Helper
const objectHelper = require('@viettv/universal-utils/object');
const merged = objectHelper.merge({ a: 1 }, { b: 2 });
const value = objectHelper.get(obj, 'nested.path', 'default');

API Documentation

File Operations

getChildFileOrFolder(directoryPath)

Lấy danh sách tất cả files và folders trong một thư mục.

const files = await utils.getChildFileOrFolder('./mydir');
// Trả về: ['file1.txt', 'file2.js', 'folder1', ...]

getLatestVersion(directoryPath, fileName, separator)

Tìm phiên bản mới nhất của một file có đánh số phiên bản.

const result = await utils.getLatestVersion('./uploads', 'document.pdf', '_v');
// Trả về: { filename: 'document_v5.pdf', version: 5, recommendedNextName: 'document_v6.pdf', nextVersion: 6 }

readExcelFile(filePath, sheetIndex)

Đọc và parse file Excel thành JSON.

const data = await utils.readExcelFile('./data.xlsx', 0);
// Trả về: [{ col1: 'value1', col2: 'value2' }, ...]

readJsonFile(filePath)

Đọc file JSON bất đồng bộ.

const config = await utils.readJsonFile('./config.json');

writeToExcelFile(data, filePath, sheetName)

Ghi dữ liệu ra file Excel.

const data = [
    { name: 'John', age: 30 },
    { name: 'Jane', age: 25 }
];
utils.writeToExcelFile(data, './output.xlsx', 'Users');

writeToJsonFile(data, filePath, prettify)

Ghi dữ liệu ra file JSON.

await utils.writeToJsonFile({ key: 'value' }, './data.json', true);

writeToTextFile(data, filePath)

Ghi text ra file.

await utils.writeToTextFile('Hello World', './output.txt');

HTTP Operations

httpGet(urlString, options)

Thực hiện HTTP GET request.

const response = await utils.httpGet('https://api.example.com/data');
// Trả về: string response data

httpPost(url, postData, options)

Thực hiện HTTP POST request.

const result = await utils.httpPost('https://api.example.com/users', {
    name: 'John',
    email: 'john@example.com'
});
// Trả về: { statusCode: 200, headers: {...}, data: {...} }

String Operations

getPositionOfSubString(string, subStr, index)

Tìm vị trí của substring tại lần xuất hiện thứ N.

const pos = utils.getPositionOfSubString('hello world hello', 'hello', 2);
// Trả về: 12

insertChar(originalString, charToInsert, position)

Chèn ký tự vào string tại vị trí chỉ định.

const result = utils.insertChar('Hello World', '!', 5);
// Trả về: 'Hello! World'

removeVietnameseTones(str)

Loại bỏ dấu tiếng Việt khỏi text.

const result = utils.removeVietnameseTones('Xin chào Việt Nam');
// Trả về: 'Xin chao Viet Nam'

Array Operations (Main Export)

Các hàm array cơ bản cũng có sẵn trong main export:

const utils = require('@viettv/universal-utils');

const merged = await utils.mergeAndGetDistinctValues([1, 2, 3], [3, 4, 5]);
const unique = await utils.getUniqueItems(users, 'id');
const grouped = utils.groupBy(items, 'category');
const grouped2D = utils.groupBy2DArray(items, 'category');

Array Helper Module

Module chuyên dụng với nhiều hàm tiện ích cho arrays:

const arrayHelper = require('@viettv/universal-utils/array');

unique(arr)

Lấy các giá trị unique từ array đơn giản.

const numbers = [1, 2, 2, 3, 4, 4, 5];
const result = arrayHelper.unique(numbers);
// Trả về: [1, 2, 3, 4, 5]

flatten(arr, depth)

Làm phẳng array đa chiều.

const nested = [1, [2, [3, [4]], 5]];
const flat = arrayHelper.flatten(nested);
// Trả về: [1, 2, 3, 4, 5]

chunk(arr, size)

Chia array thành các mảng con có kích thước cố định.

const items = [1, 2, 3, 4, 5, 6, 7];
const chunks = arrayHelper.chunk(items, 3);
// Trả về: [[1, 2, 3], [4, 5, 6], [7]]

groupBy(arr, key)

Nhóm các items trong array theo một thuộc tính.

const items = [
    { category: 'fruit', name: 'apple' },
    { category: 'fruit', name: 'banana' },
    { category: 'vegetable', name: 'carrot' }
];
const grouped = arrayHelper.groupBy(items, 'category');
// Trả về: {
//   fruit: [{ category: 'fruit', name: 'apple' }, { category: 'fruit', name: 'banana' }],
//   vegetable: [{ category: 'vegetable', name: 'carrot' }]
// }

groupBy2DArray(arr, key)

Nhóm items và trả về dạng mảng 2D.

const grouped = arrayHelper.groupBy2DArray(items, 'category');
// Trả về: [
//   [{ category: 'fruit', name: 'apple' }, { category: 'fruit', name: 'banana' }],
//   [{ category: 'vegetable', name: 'carrot' }]
// ]

shuffle(arr)

Xáo trộn array ngẫu nhiên.

const items = [1, 2, 3, 4, 5];
const shuffled = arrayHelper.shuffle(items);
// Trả về: [3, 1, 5, 2, 4] (thứ tự ngẫu nhiên)

sample(arr, count)

Lấy ngẫu nhiên item(s) từ array.

const items = [1, 2, 3, 4, 5];
const one = arrayHelper.sample(items);      // 3 (1 item ngẫu nhiên)
const three = arrayHelper.sample(items, 3); // [2, 5, 1] (3 items ngẫu nhiên)

difference(arr1, arr2)

Tìm các phần tử có trong arr1 nhưng không có trong arr2.

const diff = arrayHelper.difference([1, 2, 3, 4], [3, 4, 5, 6]);
// Trả về: [1, 2]

intersection(arr1, arr2)

Tìm các phần tử có trong cả hai arrays.

const common = arrayHelper.intersection([1, 2, 3, 4], [3, 4, 5, 6]);
// Trả về: [3, 4]

partition(arr, predicate)

Phân chia array thành hai arrays dựa trên điều kiện.

const numbers = [1, 2, 3, 4, 5, 6];
const [evens, odds] = arrayHelper.partition(numbers, n => n % 2 === 0);
// evens: [2, 4, 6]
// odds: [1, 3, 5]

countBy(arr)

Đếm số lần xuất hiện của mỗi item.

const items = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];
const counts = arrayHelper.countBy(items);
// Trả về: { apple: 3, banana: 2, orange: 1 }

sortBy(arr, key, ascending)

Sắp xếp array của objects theo một thuộc tính.

const users = [
    { name: 'John', age: 30 },
    { name: 'Jane', age: 25 },
    { name: 'Bob', age: 35 }
];
const sorted = arrayHelper.sortBy(users, 'age');
// Trả về: [{ name: 'Jane', age: 25 }, { name: 'John', age: 30 }, { name: 'Bob', age: 35 }]

includesAny(arr, values)

Kiểm tra xem array có chứa bất kỳ giá trị nào không.

const items = [1, 2, 3, 4, 5];
const hasAny = arrayHelper.includesAny(items, [6, 7, 3]);
// Trả về: true (vì 3 có trong items)

includesAll(arr, values)

Kiểm tra xem array có chứa tất cả các giá trị không.

const items = [1, 2, 3, 4, 5];
const hasAll = arrayHelper.includesAll(items, [2, 3, 4]);
// Trả về: true (tất cả values đều có trong items)

remove(arr, ...values)

Loại bỏ các items khỏi array theo giá trị.

const items = [1, 2, 3, 4, 5, 3];
const filtered = arrayHelper.remove(items, 3, 5);
// Trả về: [1, 2, 4]

take(arr, n)takeLast(arr, n)

Lấy n items đầu hoặc cuối từ array.

const items = [1, 2, 3, 4, 5];
const first3 = arrayHelper.take(items, 3);     // [1, 2, 3]
const last3 = arrayHelper.takeLast(items, 3);  // [3, 4, 5]

zip(...arrays)

Gộp nhiều arrays lại với nhau.

const names = ['John', 'Jane', 'Bob'];
const ages = [30, 25, 35];
const zipped = arrayHelper.zip(names, ages);
// Trả về: [['John', 30], ['Jane', 25], ['Bob', 35]]

range(start, end, step)

Tạo array các số trong một khoảng.

const range1 = arrayHelper.range(1, 5);     // [1, 2, 3, 4]
const range2 = arrayHelper.range(0, 10, 2); // [0, 2, 4, 6, 8]

areArraysEqual(arr1, arr2)

Kiểm tra xem hai arrays có bằng nhau không (so sánh có thứ tự). Đây là phương thức tốt nhất về hiệu suất.

arrayHelper.areArraysEqual([1, 2, 3], [1, 2, 3]); // true
arrayHelper.areArraysEqual([1, 2, 3], [3, 2, 1]); // false (thứ tự khác)
arrayHelper.areArraysEqual([1, 2], [1, 2, 3]);    // false (độ dài khác)

areArraysEqualUnordered(arr1, arr2)

Kiểm tra xem hai arrays có chứa cùng các phần tử không, bất kể thứ tự.

arrayHelper.areArraysEqualUnordered([1, 2, 3], [3, 2, 1]); // true (cùng phần tử)
arrayHelper.areArraysEqualUnordered([1, 2, 3], [1, 2, 4]); // false (phần tử khác)
arrayHelper.areArraysEqualUnordered([1, 2], [1, 2, 3]);    // false (độ dài khác)

mergeAndGetDistinctValues(arr1, arr2, assumeUnique)

Gộp hai arrays và lấy các giá trị không trùng lặp.

const result = await arrayHelper.mergeAndGetDistinctValues([1, 2, 3], [3, 4, 5]);
// Trả về: [1, 2, 3, 4, 5]

getUniqueItems(arr, keyField)

Loại bỏ duplicates từ array dựa trên một thuộc tính.

const users = [
    { id: 1, name: 'John' },
    { id: 2, name: 'Jane' },
    { id: 1, name: 'John' }
];
const unique = await arrayHelper.getUniqueItems(users, 'id');
// Trả về: [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }]

getUniqueBy(arr, keys, separator)

Loại bỏ duplicates dựa trên một hoặc nhiều thuộc tính (composite keys). Hỗ trợ cả single key và multiple keys.

// Single key
const users = [
    { email: 'john@example.com', name: 'John' },
    { email: 'jane@example.com', name: 'Jane' },
    { email: 'john@example.com', name: 'John Smith' }  // duplicate email
];
const uniqueByEmail = arrayHelper.getUniqueBy(users, 'email');
// Trả về: [
//   { email: 'john@example.com', name: 'John' },
//   { email: 'jane@example.com', name: 'Jane' }
// ]

// Multiple keys (composite key)
const tickets = [
    { class: 'first', fare: 'a' },
    { class: 'first', fare: 'a' },   // duplicate
    { class: 'first', fare: 'b' },
    { class: 'second', fare: 'a' },
    { class: 'first', fare: 'a' }    // duplicate
];
const uniqueTickets = arrayHelper.getUniqueBy(tickets, ['class', 'fare']);
// Trả về: [
//   { class: 'first', fare: 'a' },
//   { class: 'first', fare: 'b' },
//   { class: 'second', fare: 'a' }
// ]

Number Helper Module

Module chuyên dụng với nhiều hàm tiện ích cho numbers:

const numberHelper = require('@viettv/universal-utils/number');

Các hàm chính:

  • sum(arr) - Tổng các số trong array
  • average(arr) - Trung bình cộng
  • min(arr), max(arr), median(arr) - Tìm giá trị min, max, median
  • formatThousands(num, separator) - Format số với dấu phân cách nghìn
  • formatCurrency(num, currency, decimals) - Format tiền tệ
  • formatPercent(num, decimals, asDecimal) - Format phần trăm
  • formatCompact(num, decimals) - Format gọn (1.2K, 1.5M, ...)
  • round(num, decimals), roundUp(num, decimals), roundDown(num, decimals) - Làm tròn
  • randomInt(min, max), randomFloat(min, max, decimals) - Số ngẫu nhiên
  • percentChange(oldValue, newValue) - Tính % thay đổi
  • isEven(num), isOdd(num), isPrime(num) - Kiểm tra số
  • gcd(a, b), lcm(a, b) - Ước chung lớn nhất, bội chung nhỏ nhất

Xem file number.js để biết đầy đủ các functions và examples.

String Helper Module

Module chuyên dụng với nhiều hàm tiện ích cho strings:

const stringHelper = require('@viettv/universal-utils/string');

Các hàm chính:

  • toCamelCase(str), toPascalCase(str), toSnakeCase(str), toKebabCase(str), toTitleCase(str) - Chuyển đổi case
  • capitalize(str) - Viết hoa chữ cái đầu
  • reverse(str) - Đảo ngược chuỗi
  • truncate(str, length, suffix) - Cắt ngắn chuỗi
  • pad(str, length, char, direction) - Padding chuỗi
  • slugify(str) - Tạo slug URL-friendly
  • isEmpty(str), isAlpha(str), isNumeric(str), isAlphanumeric(str) - Kiểm tra chuỗi
  • isEmail(str), isUrl(str) - Kiểm tra email, URL
  • countOccurrences(str, substr) - Đếm số lần xuất hiện
  • extractNumbers(str), extractEmails(str), extractUrls(str) - Trích xuất dữ liệu
  • removeVietnameseTones(str) - Loại bỏ dấu tiếng Việt
  • mask(str, visibleChars, maskChar) - Che giấu chuỗi

Xem file string.js để biết đầy đủ các functions và examples.

Object Helper Module

Module chuyên dụng với nhiều hàm tiện ích cho objects:

const objectHelper = require('@viettv/universal-utils/object');

Các hàm chính:

  • deepClone(obj) - Sao chép sâu object
  • isEmpty(obj) - Kiểm tra object rỗng
  • keys(obj), values(obj), entries(obj), size(obj) - Lấy thông tin object
  • pick(obj, keys), omit(obj, keys) - Chọn hoặc loại bỏ keys
  • merge(...objects) - Gộp nhiều objects
  • flatten(obj, separator), unflatten(obj, separator) - Làm phẳng/mở rộng object
  • invert(obj) - Đảo ngược keys và values
  • isObject(value), hasKey(obj, key), hasKeys(obj, keys) - Kiểm tra object
  • isEqual(obj1, obj2) - So sánh sâu hai objects
  • mapValues(obj, fn), mapKeys(obj, fn), filter(obj, predicate) - Transform object
  • get(obj, path, defaultValue), set(obj, path, value), has(obj, path) - Truy cập nested properties
  • compact(obj, deep) - Loại bỏ null/undefined values

Xem file object.js để biết đầy đủ các functions và examples.

Console Operations

notify(content)

Tạo console notifications với màu sắc.

utils.notify('Operation completed').success();  // Màu xanh lá
utils.notify('Warning message').warning();      // Màu vàng
utils.notify('Error occurred').error();         // Màu đỏ
utils.notify('Information').info();             // Màu xanh dương
utils.notify('Regular log').log();              // Màu mặc định

Timer Operations

sleep(time)

Tạm dừng thực thi trong khoảng thời gian chỉ định.

await utils.sleep(1000); // Dừng 1 giây
console.log('1 giây sau...');

timeout(ms)

Tạo timeout promise.

try {
    await Promise.race([
        longRunningOperation(),
        utils.timeout(5000)
    ]);
} catch (error) {
    console.log('Operation timed out');
}

withTimeout(promise, ms)

Chạy promise với timeout.

try {
    const result = await utils.withTimeout(fetchData(), 5000);
} catch (error) {
    console.log('Operation timed out after 5 seconds');
}

Utility Functions

isEmpty(value)

Kiểm tra xem giá trị có rỗng không.

utils.isEmpty(null);        // true
utils.isEmpty('');          // true
utils.isEmpty([]);          // true
utils.isEmpty({});          // true
utils.isEmpty('hello');     // false

deepClone(obj)

Sao chép sâu một object.

const original = { a: 1, b: { c: 2 } };
const cloned = utils.deepClone(original);
cloned.b.c = 3;
console.log(original.b.c); // 2 (không bị thay đổi)

generateUUID()

Tạo UUID v4 đơn giản.

const id = utils.generateUUID();
// Trả về: 'a3f5b2c1-4d5e-4f6a-8b9c-0d1e2f3a4b5c'

Legacy Aliases

Để tương thích ngược, các alias sau vẫn được hỗ trợ:

// HTTP Operations
utils.httpGetBuiltIn(...);  // Giống httpGet
utils.createPostRequest(...); // Giống httpPost

// Array Operations
utils.mergeAndGetDistinctValuesFrom2Arrays(...); // Giống mergeAndGetDistinctValues
utils.uniq_fast(...);  // Giống getUniqueItems

Ví dụ sử dụng thực tế

Ví dụ 1: Xử lý dữ liệu từ Excel

const utils = require('@viettv/universal-utils');
const arrayHelper = require('@viettv/universal-utils/array');

async function processExcelData() {
    // Đọc dữ liệu từ Excel
    const data = await utils.readExcelFile('./users.xlsx');
    
    // Loại bỏ duplicates dựa trên email
    const uniqueUsers = await arrayHelper.getUniqueItems(data, 'email');
    
    // Nhóm theo department
    const byDepartment = arrayHelper.groupBy(uniqueUsers, 'department');
    
    // Sắp xếp theo tuổi
    const sorted = arrayHelper.sortBy(uniqueUsers, 'age');
    
    // Ghi kết quả ra file mới
    await utils.writeToExcelFile(sorted, './processed_users.xlsx');
    
    utils.notify('Xử lý hoàn tất!').success();
}

Ví dụ 2: Làm việc với API và xử lý arrays

const utils = require('@viettv/universal-utils');
const arrayHelper = require('@viettv/universal-utils/array');

async function fetchAndProcessData() {
    try {
        // Fetch data từ API với timeout
        const response = await utils.withTimeout(
            utils.httpGet('https://api.example.com/products'),
            5000
        );
        
        const products = JSON.parse(response);
        
        // Phân loại products
        const [inStock, outOfStock] = arrayHelper.partition(
            products, 
            p => p.stock > 0
        );
        
        // Nhóm theo category
        const byCategory = arrayHelper.groupBy(inStock, 'category');
        
        // Lấy 10 sản phẩm ngẫu nhiên
        const featured = arrayHelper.sample(inStock, 10);
        
        // Lưu kết quả
        await utils.writeToJsonFile({
            inStock: inStock.length,
            outOfStock: outOfStock.length,
            categories: Object.keys(byCategory),
            featured
        }, './products-summary.json');
        
        utils.notify('Data processed successfully').success();
    } catch (error) {
        utils.notify(`Error: ${error.message}`).error();
    }
}

Ví dụ 3: Xử lý files với versioning

const utils = require('@viettv/universal-utils');

async function saveWithVersion() {
    // Lấy version mới nhất
    const versionInfo = await utils.getLatestVersion(
        './backups',
        'database.json',
        '_v'
    );
    
    console.log(`Current version: ${versionInfo.version}`);
    console.log(`Next version: ${versionInfo.nextVersion}`);
    
    // Đọc dữ liệu hiện tại
    const data = await utils.readJsonFile('./database.json');
    
    // Lưu với version mới
    await utils.writeToJsonFile(
        data,
        `./backups/${versionInfo.recommendedNextName}`
    );
    
    utils.notify(`Saved as ${versionInfo.recommendedNextName}`).success();
}

Requirements

  • Node.js >= 12.0.0

Dependencies

  • xlsx - Để xử lý files Excel

License

MIT

Author

Your Name your.email@example.com

Repository

https://github.com/1zuna/npm-utilities

Issues

https://github.com/1zuna/npm-utilities/issues