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

Nested functions do not evaluate arguments #712

Open
Jaspooky opened this issue Sep 18, 2024 · 1 comment
Open

Nested functions do not evaluate arguments #712

Jaspooky opened this issue Sep 18, 2024 · 1 comment

Comments

@Jaspooky
Copy link

Jaspooky commented Sep 18, 2024

When functions are not defined at the top level but instead attached as part of an object, their arguments don't appear to actually be evaluated. For example below, reverseString works fine when declared as a top level function, but not when referenced as a property of a wrapping object.

MRE

const jsonata = require('jsonata');
 
 const lib = () => ({
   reverseString: (str) => str.split('').reverse().join(''),
 });
 
 const createJsonata = (expression) => {
   const instance = jsonata(expression);

   instance.registerFunction('lib', lib);
   instance.registerFunction('reverseString', lib().reverseString);
 
   return instance;
 };
 
 const data = { name: 'Jasper' };
 
 const works = createJsonata("( $str := $.name; $lib().reverseString($str) )")
   .evaluate(data); //?
   // 'repsaJ'
 
 const alsoWorks = createJsonata("$reverseString($.name)")
   .evaluate(data); //?
   // 'repsaJ'
 
 const fails = createJsonata("$lib().reverseString($.name)")
   .evaluate(data); //?
   // TypeError: Cannot read properties of undefined (reading 'split')
@markmelville
Copy link
Contributor

I believe it's because . is not really a property access operator, but the a path mapping operator. The docs say: "the LHS [is] known as the context and is used as the basis for any relative path expression on the RHS, and is accessible in the RHS expression using the $ symbol." IOW, a . changes what $ refers to. So in the first example you bind the name to a variable. In the second example there is no . (before the one to get the name). In the third, the $ refers to the the lib object, and there is no property "name" on that object. Shooting from the hip here, but these expressions may work:

  • $lib().reverseString($$.name)
  • $lookup($lib(),"reverseString")($.name)

@mattbaileyuk mattbaileyuk removed the bug label Oct 1, 2024
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

3 participants