Math Field (Mathematical Expression Field Formatter)

A simple lexer and parser that can compute simple mathematical operations using the most basic operators `+, -, *, /` and can correctly handle parentheses `()` and floating point operations (decimal numbers). It can NOT currently handle negative numbers or unary operations.

It is implemented as a Drupal 8 service module and provides a text field formatter.

The formatter currently displays errors inline.

Requirements

* Drupal 8.x version

Installation

Download, install and enable as you normally install a Drupal 8 module hosted on drupal.org

composer require drupal/math_field
drush en math_field

Usage

After enabling the module create a `text field` in your content type and choose `Math field formatter` as a formatter at admin/structure/types/manage/CONTENT_TYPE/display

The formatter will display both the expression and the result (or error message):
(1 + 2) * 4 = 12

The result will be revealed on hover with a delayed CSS animation.

Features

1. The Parser needs to be able to compute simple mathematical operations using the most basic operators (+, -, *, /) without using eval().
For example: “10 + 20 - 30 + 15 * 5” should return 75.
2. Make sure you take care of operator precedence using infix notation.
3. Provide a field formatter plugin in a Drupal 8 module that uses this Service.
4. Deliver the work as a Drupal 8 site with the custom module in a git repository.
5. Provide a simple unit test with a data provider (@dataProvider) that tests the tokenization (lexing) and parsing of a few different computations.
6. Provide a GraphQL field formatter so that the field can be consumed on the frontend via GraphQL. (Under development)
7. Add a frontend component in a template language (Twig, React) of your choice that will animate the calculation in the frontend, i.e. you first show the entire formula and on-hover, the text transitions into the computed outcome.

Submission

You need to make sure that by the end of the assessment everything needed is handed in as a Drupal repository. Besides implementing the requirements, the Drupal repository needs to specify a README document with all steps needed to install and run your code.

Inspiration

  1. Initial development was done by Giorgos Kontopoulos as a test exercise (github).
  2. Shunting-yard algorithm (wikipedia)
  3. University of Cambridge
  4. Rules (D8 module)
  5. Parsing and lexing
  6. https://github.com/vuchkov/math-php
  7. https://github.com/vuchkov/math-parser
Supporting organizations: 
Initial development

Project information

Releases