daily pastebin goal
69%
SHARE
TWEET

Untitled

a guest Jun 13th, 2018 48 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const { equal } = require('assert')
  2.  
  3. const add = {
  4.     name: 'ADD',
  5.     fn(...args) {
  6.         return args.map(x => Number(x)).filter(Boolean).reduce((sum, x) => sum + x, 0)
  7.     }
  8. }
  9.  
  10. const sub = {
  11.     name: 'SUB',
  12.     fn(...args) {
  13.         return args.map(x => Number(x)).filter(Boolean).reduce((sum, x) => sum - x)
  14.     }
  15. }
  16.  
  17. const FUNCTIONS = [
  18.     add,
  19.     sub
  20. ]
  21.  
  22. const isFn = (input) =>
  23.     /.+\s*\(.+\)/.test(input)
  24.  
  25.  
  26. const excel = (input) => {
  27.  
  28.     const token = /^(\w+)\s*\((.+)\)/.exec(input)
  29.  
  30.     if (!token) throw new Error('no function to parse')
  31.  
  32.     const firstFunction = token[1].trim();
  33.     const found = FUNCTIONS.find(({ name }) => name === firstFunction.toUpperCase())
  34.     if (!found) throw new Error(`unknown ${found} function`);
  35.  
  36.     const fn = found.fn
  37.  
  38.     const args =
  39.         token[2]
  40.             .split(/,(?![^,]+\))/)
  41.             .map(x => x.trim())
  42.             .map(x => isFn(x) ? excel(x) : x);
  43.  
  44.     return fn(...args);
  45. }
  46.  
  47. equal(
  48.     excel('ADD(1, 2)'),
  49.     3
  50. )
  51.  
  52. equal(
  53.     excel('ADD(1, 2, 3, 4)'),
  54.     10
  55. )
  56.  
  57. equal(
  58.     excel('SUB(9, 3)'),
  59.     6
  60. )
  61.  
  62. equal(
  63.     excel('ADD(1, 2, SUB(ADD(5, 4), 3))'),
  64.     9
  65. )
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top