f-matches: Composable version of Lodash.matches()
An utility used by Lebab for complex matching of AST nodes.
The package exports 4 curried functions:
matches :: Pattern -> Obj -> (Bool|Obj)
extract :: Name -> Pattern -> Obj -> (Bool|Obj)
extractAny :: Name -> Obj -> (Bool|Obj)
matchesLength :: Pattern -> Array -> (Bool|Obj)
For details, just read the source, it's really small.
Alternatively, read how Lebab uses this for patterns in syntax trees.
Example
import {matches, matchesLength, extract} from "f-matches";
const isStringLiteral = matches({
"type": "Literal",
"value": (v) => typeof v === 'string',
});
const isRequireDeclarator = matches({
"type": "VariableDeclarator",
"id": extract("local", {
"type": "Identifier",
}),
"init": {
"type": "CallExpression",
"callee": {
"type": "Identifier",
"name": "require"
},
"arguments": matchesLength([
extract("source", isStringLiteral),
]),
},
});
const isRequire = matches({
"type": "VariableDeclaration",
"declarations": matchesLength([
isRequireDeclarator,
]),
"kind": "var",
});
estraverse.replace(ast, {
enter(node) {
const match = isRequire(node);
if (match) {
return {
"type": "ImportDeclaration",
"specifiers": [
{
"type": "ImportDefaultSpecifier",
"local": match.local
}
],
"source": match.source
};
}
}
});