vitalets / react-native-extended-stylesheet

Extended StyleSheets for React Native
MIT License
2.93k stars 132 forks source link

Support for complex operations #39

Closed joemckie closed 7 years ago

joemckie commented 7 years ago

I saw the commit at #633058c and thought complex operations would be a really handy feature actually. What do you think?

vitalets commented 7 years ago

I agree it can be useful. But also not trivial to implement. We can have a look on libs mentioned in [this SO question].(http://stackoverflow.com/questions/2276021/evaluating-a-string-as-a-mathematical-expression-in-javascript)

Another thought is to use value as a function for that. This already works:

{
  lineHeight: () => EStyleSheet.value('$x') * EStyleSheet.value('$y') + 1,
}

Maybe just make it less verbose:

import EStyleSheet, {val} from 'react-native-extended-stylesheet';
{
  lineHeight: () => val('$x') * val('$y') + 1,
}
joemckie commented 7 years ago

The way I envisioned it working was to create an array of operations from the string and to reduce it to a single value.

Pseudo-code, but something like this:

// StyleSheet code
{
  height: '$height + $height2 - 20'
}

// Turns to:
[
  {operator: '+', v1: '$height', v2: '$height2'}
  {operator: '-', v1: null, v2: '20'}
].reduce(acc, op) => {
  op.v1 = acc;
  acc = exec(op);
  return acc;
}, 0);

The problem I can see with trying to do it this way would be applying the correct order of BODMAS... Maybe it would be a better idea to let the user do this themselves 😅

vitalets commented 7 years ago

Finally value as a function should be sufficient enough for complex operations.