Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

unsaved parsers in namedSequenceOf #112

Open
Fredderic opened this issue Jan 1, 2024 · 0 comments
Open

unsaved parsers in namedSequenceOf #112

Fredderic opened this issue Jan 1, 2024 · 0 comments

Comments

@Fredderic
Copy link

This is a small but mighty change that I consider absolutely amazing:

  • Pass in an initialiser object so we don't have to .map to add fixed fields
  • Don't bother saving fields that are not a string (eg. null)

This simple change replaced most of my uses of A.coroutine, and avoids having to map my namedSequenceOf's to remove a scratch field, or inject static ones.

export function namedSequenceOf(pairedParsers, template) {
	return new Parser(function namedSequenceOf$state(state) {
		if (state.isError)
			return state;
		const results = {};
		if ( template ) { // copy the template into results
			Object.assign(results, template);
		}
		let nextState = state;
		for (const [key, parser] of pairedParsers) {
			const out = parser.p(nextState);
			if (out.isError) {
				return out;
			}
			else {
				nextState = out;
				if ( typeof key === 'string' ) { // don't set null keys
					results[key] = out.result;
				}
			}
		}
		return updateResult(nextState, results);
	});
}

Plus, WeakValueMap (why isn't that built into JavaScript?!?) caching a bunch of the terminal parsers, and the mass decodes of the regex parser, also make for a huge improvement. (I also export those wrapped parsers as xxxUncached — though they are, but they won't be if WeakRef isn't available and I switch to a regular Map, so the name actually means "don't do dumb caching".) I apply these changes through a shim library that imports Arcsecond, and exports everything again with the handful of changes — I strongly recommend doing the same (the only issue with the shim library, is terminal parsers being used internally, but I haven't noticed any).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant