68 lines
2.1 KiB
JavaScript
68 lines
2.1 KiB
JavaScript
require('./index');
|
|
|
|
let passed = 0;
|
|
let failed = 0;
|
|
|
|
function assert(desc, condition) {
|
|
if (condition) {
|
|
console.log(`\x1b[32m ✓ ${desc}\x1b[0m`);
|
|
passed++;
|
|
} else {
|
|
console.log(`\x1b[31m ✗ ${desc}\x1b[0m`);
|
|
failed++;
|
|
}
|
|
}
|
|
|
|
function group(name) {
|
|
console.log(`\n\x1b[36m─── ${name} ───\x1b[0m`);
|
|
}
|
|
|
|
// ===== Object.getPro =====
|
|
group('Object.getPro');
|
|
const obj = { a: { b: { c: 1 } }, 'x.y': { z: 2 } };
|
|
assert("getPro('a.b.c') === 1", obj.getPro('a.b.c') === 1);
|
|
assert("getPro('a.b.d', 'default') === 'default'", obj.getPro('a.b.d', 'default') === 'default');
|
|
assert("getPro(\"['x.y'].z\") === 2", obj.getPro("['x.y'].z") === 2);
|
|
assert("getPro('missing', 42) === 42", obj.getPro('missing', 42) === 42);
|
|
|
|
// ===== Object.setPro =====
|
|
group('Object.setPro');
|
|
const obj2 = {};
|
|
obj2.setPro('foo.bar.baz', 'hello');
|
|
assert("setPro 嵌套赋值", obj2.foo.bar.baz === 'hello');
|
|
obj2.setPro("['a.b'].c", 99);
|
|
assert("setPro 特殊键名", obj2['a.b'].c === 99);
|
|
|
|
// ===== Array Pro 方法 =====
|
|
const arr = [
|
|
{ user: { name: 'Alice' } },
|
|
{ user: { name: 'Bob' } },
|
|
null,
|
|
{ user: { name: 'Charlie' } },
|
|
];
|
|
|
|
group('Array.findPro');
|
|
assert("回调 findPro(t=>t>1)", [1, 2, 3].findPro((t) => t > 1) === 2);
|
|
assert("key-value findPro('user.name','Bob')", arr.findPro('user.name', 'Bob').user.name === 'Bob');
|
|
assert("单值 findPro('cc')", ['aa', 'bb', 'cc'].findPro('cc') === 'cc');
|
|
|
|
group('Array.filterPro');
|
|
assert("key-value filterPro", arr.filterPro('user.name', 'Alice').length === 1);
|
|
assert("单值 filterPro(2)", [1, 2, 2, 3].filterPro(2).length === 2);
|
|
|
|
group('Array.findIndexPro');
|
|
assert("findIndexPro", arr.findIndexPro('user.name', 'Charlie') === 3);
|
|
|
|
group('Array.findLastPro');
|
|
assert("findLastPro", arr.findLastPro('user.name', 'Bob').user.name === 'Bob');
|
|
|
|
group('Array.somePro / everyPro');
|
|
assert("somePro", arr.somePro('user.name', 'Alice') === true);
|
|
assert("everyPro false", arr.everyPro('user.name', 'Alice') === false);
|
|
assert("everyPro true", ['a', 'a'].everyPro('a') === true);
|
|
|
|
// 汇总
|
|
console.log(`\n\x1b[33m共 ${passed + failed} 项,${passed} 通过,${failed} 失败\x1b[0m`);
|
|
|
|
process.exit(failed > 0 ? 1 : 0);
|