2
0
mirror of https://github.com/tenrok/BBob.git synced 2026-05-21 13:24:05 +03:00
Files
bbob/packages/bbob-core/src/utils.ts
T
Nikolay Kost 270f5645f8 fix(#206): TagNode.create now with null content argument by default (#233)
* fix: TagNode.create with null content by default

* Create five-meals-sing.md

* fix: tests

* fix(preset): types inference

* fix: preset types

* fix: preset types

* fix: lock file, parser and utils

* refactor: move types to separate package

* fix(preset): add @bbob/core to dev deps

* fix(preset): lock file

* test(preset-vue): create tags

* test(preset-vue): tests

* chore(nx): fix nx cover deps

* chore: changesets
2024-06-24 01:32:15 +03:00

73 lines
1.9 KiB
TypeScript

/* eslint-disable no-plusplus */
import { IterateCallback } from "@bbob/types";
const isObj = (value: unknown): value is Record<string, unknown> => (typeof value === 'object' && value !== null);
const isBool = (value: unknown): value is boolean => (typeof value === 'boolean');
export function iterate<Content, Iterable = ArrayLike<Content> | Content>(t: Iterable, cb: IterateCallback<Content>): Iterable {
const tree = t;
if (Array.isArray(tree)) {
for (let idx = 0; idx < tree.length; idx++) {
tree[idx] = iterate(cb(tree[idx]), cb);
}
} else if (isObj(tree) && 'content' in tree) {
iterate(tree.content, cb);
}
return tree;
}
export function same(expected: unknown, actual: unknown): boolean {
if (typeof expected !== typeof actual) {
return false;
}
if (!isObj(expected) || expected === null) {
return expected === actual;
}
if (Array.isArray(expected)) {
return expected.every((exp) => [].some.call(actual, (act) => same(exp, act)));
}
if (isObj(expected) && isObj(actual)) {
return Object.keys(expected).every((key) => {
const ao = actual[key];
const eo = expected[key];
if (isObj(eo) && isObj(ao)) {
return same(eo, ao);
}
if (isBool(eo)) {
return eo !== (ao === null);
}
return ao === eo;
});
}
return false
}
export function match<Content, Iterable = ArrayLike<Content>>(
t: Iterable,
expression: Content | ArrayLike<Content>,
cb: IterateCallback<Content>
) {
if (Array.isArray(expression)) {
return iterate<Content, Iterable>(t, (node) => {
for (let idx = 0; idx < expression.length; idx++) {
if (same(expression[idx], node)) {
return cb(node);
}
}
return node;
})
}
return iterate<Content, Iterable>(t, (node) => (same(expression, node) ? cb(node) : node));
}