Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const { equal } = require('assert')
- const add = {
- name: 'ADD',
- fn(...args) {
- return args.map(x => Number(x)).filter(Boolean).reduce((sum, x) => sum + x, 0)
- }
- }
- const sub = {
- name: 'SUB',
- fn(...args) {
- return args.map(x => Number(x)).filter(Boolean).reduce((sum, x) => sum - x)
- }
- }
- const FUNCTIONS = [
- add,
- sub
- ]
- const isFn = (input) =>
- /.+\s*\(.+\)/.test(input)
- const excel = (input) => {
- const token = /^(\w+)\s*\((.+)\)/.exec(input)
- if (!token) throw new Error('no function to parse')
- const firstFunction = token[1].trim();
- const found = FUNCTIONS.find(({ name }) => name === firstFunction.toUpperCase())
- if (!found) throw new Error(`unknown ${found} function`);
- const fn = found.fn
- const args =
- token[2]
- .split(/,(?![^,]+\))/)
- .map(x => x.trim())
- .map(x => isFn(x) ? excel(x) : x);
- return fn(...args);
- }
- equal(
- excel('ADD(1, 2)'),
- 3
- )
- equal(
- excel('ADD(1, 2, 3, 4)'),
- 10
- )
- equal(
- excel('SUB(9, 3)'),
- 6
- )
- equal(
- excel('ADD(1, 2, SUB(ADD(5, 4), 3))'),
- 9
- )
Add Comment
Please, Sign In to add comment