{"id":13879180,"url":"https://github.com/rubysolo/dentaku","last_synced_at":"2025-07-16T15:31:40.670Z","repository":{"id":2272451,"uuid":"3229121","full_name":"rubysolo/dentaku","owner":"rubysolo","description":"math and logic formula parser and evaluator","archived":false,"fork":false,"pushed_at":"2025-06-27T18:01:47.000Z","size":717,"stargazers_count":913,"open_issues_count":17,"forks_count":164,"subscribers_count":26,"default_branch":"main","last_synced_at":"2025-07-06T16:25:34.335Z","etag":null,"topics":["calculator","evaluate-expressions","formula","safeeval"],"latest_commit_sha":null,"homepage":"","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/rubysolo.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2012-01-20T19:49:00.000Z","updated_at":"2025-06-27T18:01:51.000Z","dependencies_parsed_at":"2023-12-06T20:28:11.574Z","dependency_job_id":"8e1a737b-dc4e-42f5-a6fc-8c4142a9f154","html_url":"https://github.com/rubysolo/dentaku","commit_stats":{"total_commits":456,"total_committers":82,"mean_commits":5.560975609756097,"dds":"0.45175438596491224","last_synced_commit":"9418c8ca1ea9c85ded54eaf22370b29c88487047"},"previous_names":[],"tags_count":54,"template":false,"template_full_name":null,"purl":"pkg:github/rubysolo/dentaku","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rubysolo%2Fdentaku","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rubysolo%2Fdentaku/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rubysolo%2Fdentaku/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rubysolo%2Fdentaku/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/rubysolo","download_url":"https://codeload.github.com/rubysolo/dentaku/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rubysolo%2Fdentaku/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":264720211,"owners_count":23653712,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["calculator","evaluate-expressions","formula","safeeval"],"created_at":"2024-08-06T08:02:12.397Z","updated_at":"2025-07-16T15:31:40.658Z","avatar_url":"https://github.com/rubysolo.png","language":"Ruby","funding_links":[],"categories":["Ruby"],"sub_categories":[],"readme":"Dentaku\n=======\n\n[![Join the chat at https://gitter.im/rubysolo/dentaku](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/rubysolo/dentaku?utm_source=badge\u0026utm_medium=badge\u0026utm_campaign=pr-badge\u0026utm_content=badge)\n[![Gem Version](https://badge.fury.io/rb/dentaku.png)](http://badge.fury.io/rb/dentaku)\n\n\nDESCRIPTION\n-----------\n\nDentaku is a parser and evaluator for a mathematical and logical formula\nlanguage that allows run-time binding of values to variables referenced in the\nformulas.  It is intended to safely evaluate untrusted expressions without\nopening security holes.\n\nEXAMPLE\n-------\n\nThis is probably simplest to illustrate in code:\n\n```ruby\ncalculator = Dentaku::Calculator.new\ncalculator.evaluate('10 * 2')\n#=\u003e 20\n```\n\nOkay, not terribly exciting.  But what if you want to have a reference to a\nvariable, and evaluate it at run-time?  Here's how that would look:\n\n```ruby\ncalculator.evaluate('kiwi + 5', kiwi: 2)\n#=\u003e 7\n```\n\nTo enter a case sensitive mode, just pass an option to the calculator instance:\n\n```ruby\ncalculator.evaluate('Kiwi + 5', Kiwi: -2, kiwi: 2)\n#=\u003e 7\ncalculator = Dentaku::Calculator.new(case_sensitive: true)\ncalculator.evaluate('Kiwi + 5', Kiwi: -2, kiwi: 2)\n#=\u003e 3\n```\n\nYou can also store the variable values in the calculator's memory and then\nevaluate expressions against those stored values:\n\n```ruby\ncalculator.store(peaches: 15)\ncalculator.evaluate('peaches - 5')\n#=\u003e 10\ncalculator.evaluate('peaches \u003e= 15')\n#=\u003e true\n```\n\nFor maximum CS geekery, `bind` is an alias of `store`.\n\nDentaku understands precedence order and using parentheses to group expressions\nto ensure proper evaluation:\n\n```ruby\ncalculator.evaluate('5 + 3 * 2')\n#=\u003e 11\ncalculator.evaluate('(5 + 3) * 2')\n#=\u003e 16\n```\n\nThe `evaluate` method will return `nil` if there is an error in the formula.\nIf this is not the desired behavior, use `evaluate!`, which will raise an\nexception.\n\n```ruby\ncalculator.evaluate('10 * x')\n#=\u003e nil\ncalculator.evaluate!('10 * x')\nDentaku::UnboundVariableError: Dentaku::UnboundVariableError\n```\n\nDentaku has built-in functions (including `if`, `not`, `min`, `max`, `sum`, and\n`round`) and the ability to define custom functions (see below). Functions\ngenerally work like their counterparts in Excel:\n\n```ruby\ncalculator.evaluate('SUM(1, 1, 2, 3, 5, 8)')\n#=\u003e 20\n\ncalculator.evaluate('if (pears \u003c 10, 10, 20)', pears: 5)\n#=\u003e 10\ncalculator.evaluate('if (pears \u003c 10, 10, 20)', pears: 15)\n#=\u003e 20\n```\n\n`round` can be called with or without the number of decimal places:\n\n```ruby\ncalculator.evaluate('round(8.2)')\n#=\u003e 8\ncalculator.evaluate('round(8.2759, 2)')\n#=\u003e 8.28\n```\n\n`round` follows rounding rules, while `roundup` and `rounddown` are `ceil` and\n`floor`, respectively.\n\nIf you're too lazy to be building calculator objects, there's a shortcut just\nfor you:\n\n```ruby\nDentaku('plums * 1.5', plums: 2)\n#=\u003e 3.0\n```\n\nPERFORMANCE\n-----------\n\nThe flexibility and safety of Dentaku don't come without a price.  Tokenizing a\nstring, parsing to an AST, and then evaluating that AST are about 2 orders of\nmagnitude slower than doing the same math in pure Ruby!\n\nThe good news is that most of the time is spent in the tokenization and parsing\nphases, so if performance is a concern, you can enable AST caching:\n\n```ruby\nDentaku.enable_ast_cache!\n```\n\nAfter this, Dentaku will cache the AST of each formula that it evaluates, so\nsubsequent evaluations (even with different values for variables) will be much\nfaster -- closer to 4x native Ruby speed.  As usual, these benchmarks should be\nconsidered rough estimates, and you should measure with representative formulas\nfrom your application.  Also, if new formulas are constantly introduced to your\napplication, AST caching will consume more memory with each new formula.\n\nBUILT-IN OPERATORS AND FUNCTIONS\n---------------------------------\n\nMath: `+`, `-`, `*`, `/`, `%`, `^`, `|`, `\u0026`, `\u003c\u003c`, `\u003e\u003e`\n\nAlso, all functions from Ruby's Math module, including `SIN`, `COS`, `TAN`, etc.\n\nComparison: `\u003c`, `\u003e`, `\u003c=`, `\u003e=`, `\u003c\u003e`, `!=`, `=`,\n\nLogic: `IF`, `AND`, `OR`, `XOR`, `NOT`, `SWITCH`\n\nNumeric: `MIN`, `MAX`, `SUM`, `AVG`, `COUNT`, `ROUND`, `ROUNDDOWN`, `ROUNDUP`, `ABS`, `INTERCEPT`\n\nSelections: `CASE` (syntax see [spec](https://github.com/rubysolo/dentaku/blob/main/lib/dentaku/ast/case.rb))\n\nString: `LEFT`, `RIGHT`, `MID`, `LEN`, `FIND`, `SUBSTITUTE`, `CONCAT`, `CONTAINS`\n\nCollection: `MAP`, `FILTER`, `ALL`, `ANY`, `PLUCK`\n\nRESOLVING DEPENDENCIES\n----------------------\n\nIf your formulas rely on one another, they may need to be resolved in a\nparticular order. For example:\n\n```ruby\ncalc = Dentaku::Calculator.new\ncalc.store(monthly_income: 50)\nneed_to_compute = {\n  income_taxes: \"annual_income / 5\",\n  annual_income: \"monthly_income * 12\"\n}\n```\n\nIn the example, `annual_income` needs to be computed (and stored) before\n`income_taxes`.\n\nDentaku provides two methods to help resolve formulas in order:\n\n#### Calculator.dependencies\nPass a (string) expression to Dependencies and get back a list of variables (as\n`:symbols`) that are required for the expression. `Dependencies` also takes\ninto account variables already (explicitly) stored into the calculator.\n\n```ruby\ncalc.dependencies(\"monthly_income * 12\")\n#=\u003e []\n# (since monthly_income is in memory)\n\ncalc.dependencies(\"annual_income / 5\")\n#=\u003e [:annual_income]\n```\n\n#### Calculator.solve! / Calculator.solve\nHave Dentaku figure out the order in which your formulas need to be evaluated.\n\nPass in a hash of `{eventual_variable_name: \"expression\"}` to `solve!` and\nhave Dentaku resolve dependencies (using `TSort`) for you.\n\nRaises `TSort::Cyclic` when a valid expression order cannot be found.\n\n```ruby\ncalc = Dentaku::Calculator.new\ncalc.store(monthly_income: 50)\nneed_to_compute = {\n  income_taxes:  \"annual_income / 5\",\n  annual_income: \"monthly_income * 12\"\n}\ncalc.solve!(need_to_compute)\n#=\u003e {annual_income: 600, income_taxes: 120}\n\ncalc.solve!(\n  make_money: \"have_money\",\n  have_money: \"make_money\"\n}\n#=\u003e raises TSort::Cyclic\n```\n\n`solve!` will also raise an exception if any of the formulas in the set cannot\nbe evaluated (e.g. raise `ZeroDivisionError`).  The non-bang `solve` method will\nfind as many solutions as possible and return the symbol `:undefined` for the\nproblem formulas.\n\nINLINE COMMENTS\n---------------------------------\n\nIf your expressions grow long or complex, you may add inline comments for future\nreference. This is particularly useful if you save your expressions in a model.\n\n```ruby\ncalculator.evaluate('kiwi + 5 /* This is a comment */', kiwi: 2)\n#=\u003e 7\n```\n\nComments can be single or multi-line. The following are also valid.\n\n```\n/*\n * This is a multi-line comment\n */\n\n/*\n This is another type of multi-line comment\n */\n```\n\nEXTERNAL FUNCTIONS\n------------------\n\nI don't know everything, so I might not have implemented all the functions you\nneed.  Please implement your favorites and send a pull request!  Okay, so maybe\nthat's not feasible because:\n\n1. You can't be bothered to share\n1. You can't wait for me to respond to a pull request, you need it `NOW()`\n1. The formula is the secret sauce for your startup\n\nWhatever your reasons, Dentaku supports adding functions at runtime.  To add a\nfunction, you'll need to specify a name, a return type, and a lambda that\naccepts all function arguments and returns the result value.\n\nHere's an example of adding a function named `POW` that implements\nexponentiation.\n\n```ruby\n\u003e c = Dentaku::Calculator.new\n\u003e c.add_function(:pow, :numeric, -\u003e(mantissa, exponent) { mantissa ** exponent })\n\u003e c.evaluate('POW(3,2)')\n#=\u003e 9\n\u003e c.evaluate('POW(2,3)')\n#=\u003e 8\n```\n\nHere's an example of adding a variadic function:\n\n```ruby\n\u003e c = Dentaku::Calculator.new\n\u003e c.add_function(:max, :numeric, -\u003e(*args) { args.max })\n\u003e c.evaluate 'MAX(8,6,7,5,3,0,9)'\n#=\u003e 9\n```\n\n(However both of these are already built-in -- the `^` operator and the `MAX`\nfunction)\n\nFunctions can be added individually using Calculator#add_function, or en masse\nusing Calculator#add_functions.\n\nFUNCTION ALIASES\n----------------\n\nEvery function can be aliased by synonyms. For example, it can be useful if\nyour application is multilingual.\n\n```ruby\nDentaku.aliases = {\n  round: ['rrrrround!', 'округлить']\n}\n\nDentaku('rrrrround!(8.2) + округлить(8.4)') # the same as round(8.2) + round(8.4)\n# 16\n```\n\nAlso, if you need thread-safe aliases you can pass them to `Dentaku::Calculator`\ninitializer:\n\n```ruby\naliases = {\n  round: ['rrrrround!', 'округлить']\n}\nc = Dentaku::Calculator.new(aliases: aliases)\nc.evaluate('rrrrround!(8.2) + округлить(8.4)')\n# 16\n```\n\nTHANKS\n------\n\nBig thanks to [ElkStone Basements](http://www.elkstonebasements.com/) for\nallowing me to extract and open source this code.  Thanks also to all the\n[contributors](https://github.com/rubysolo/dentaku/graphs/contributors)!\n\n\nLICENSE\n-------\n\n(The MIT License)\n\nCopyright © 2012-2022 Solomon White\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the ‘Software’), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED ‘AS IS’, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frubysolo%2Fdentaku","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frubysolo%2Fdentaku","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frubysolo%2Fdentaku/lists"}