[
  {
    "path": ".gitignore",
    "content": "# Compiled Object files, Static and Dynamic libs (Shared Objects)\n*.o\n*.a\n*.so\n\n# Folders\n_obj\n_test\n\n# Architecture specific extensions/prefixes\n*.[568vq]\n[568vq].out\n\n*.cgo1.go\n*.cgo2.c\n_cgo_defun.c\n_cgo_gotypes.go\n_cgo_export.*\n\n_testmain.go\n\n*.exe\n*.test\n*.prof\n\n\n# Gogland IDE files\n.idea/\n\n# ENV variables/secrets\n.envrc\n\n# generated library file\nlib.js\n\n# binary\ngg-flip"
  },
  {
    "path": "LICENSE",
    "content": "The MIT License (MIT)\n\nCopyright (c) 2018 Avinash Sajjanshetty <hi@avi.im>\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"
  },
  {
    "path": "README.md",
    "content": "# GG Flip\n\nDonald Knuth described in one of his TAOCP books that flipping the sign of a number is one of the hardest problems in Computer Science. But that was in the 60s. Thanks to years of research and after numerous publications, today have some interesting ways to do the same. Consider this:\n\n```javascript\nx = 5\n// get -5\nx -= x*2;\n```\n\nAbove is one of the simplest and most efficient ways to flip the sign of a number. It uses the 'minimal' approach and there is now a [popular npm library](https://github.com/avinassh/sign-flip) based on it. It actually works and is highly performant:\n\n![performance-report](perf.png)\n\nBut as you can see, in today's webscale world flipping ~4000 signs per second wouldn't cut it. I started to look into the ways to improve it and started reading the code of V8 engine. My C is rusty, but I was able to read through most of the code and understand it. Turns out V8 highly optimises the switch blocks and they are faster compared to any other control statements. I decided to make use of this and implement a better sign flip. GG Flip is the result.\n\nGG Flip is a Golang library which generates the Javascript sign flip library. I preferred Go because lack of generics seemed like a good design choice. This code has no external dependencies, you can run:\n\n```\ngit clone https://github.com/avinassh/gg-flip.git\ncd gg-flip\ngo run main.go\n```\n\nAbove code generates highly readable file `lib.js`, which is:\n\n```javascript\nfunction signFlip(num) {\n    switch (num) {\n        case 0:\n            return -0;\n        case -0:\n            return 0;\n        case 1:\n            return -1;\n        case -1:\n            return 1;\n        // ...\n        case 9:\n            return -9;        \n        case -9:\n            return 9;\n        // ...\n        case 9007199254740991:\n            return -9007199254740991;\n        case -9007199254740991:\n            return 9007199254740991;\n        default:\n            return num-num*2;\n    }\n}\n```\n\nThanks to V8 and their clever switch block optimizations, the above code becomes highly performant. If the jumps in switch take a long time, then it fallbacks to the default, which flips the sign using minimal approach. It's a win-win! See the performance by yourself:\n\n![performance-report2](perf2.png)\n\nEven in low memory environments (old computers, internet explorer, iPhones with low battery), GG Flip performs almost twice as fast compared to the minimal approach and in the usual environments, it's almost 10x faster than the usual method and 4x faster than the minimal approach. Currently, GG Flip works only with the integers and for floats, it fallbacks to default switch case. In the next version, I will include all the float numbers, so that for floats also the performance remains same.\n\nThe final lib size is few GBs, so distribution may become a problem. But I am talking with popular CDN providers like Google, Cloudflare etc to ship this library directly. I am planning to send a PR to Javascript with this library so that GG Flip comes as a standard library as part of the glorious language.\n\nI am also exploring Blockchain to see if this library can be distributed securely and quickly, to everyone. Bitcoin Cash which is a fork of Bitcoin, uses 4MB per blocks and hence might be a good candidate to distribute the GG Flip.\n\n## GG Flip as a Service\n\nI am now providing GG Flip as a web service, check - [GaS](https://avi.im/gg-flip/). Now, with a simple API request, you can flip the sign of numbers and get all the benefits. GaS is hosted on Cloud and hence is very fast.\n\n## License\n\nThe mighty MIT license. Please check `LICENSE` for more details.\n"
  },
  {
    "path": "chart.html",
    "content": "<!DOCTYPE html>\n<html>\n<head>\n  <title></title>\n  <script type=\"text/javascript\" src=\"https://www.gstatic.com/charts/loader.js\"></script>\n</head>\n<body>\n  <div id=\"chart_div\"></div>\n  <script type=\"text/javascript\">\n    google.charts.load('current', {packages: ['corechart', 'bar']});\n    google.charts.setOnLoadCallback(drawBasic);\n\n    function drawBasic() {\n          var data = google.visualization.arrayToDataTable([\n            ['Operation', 'Signs Flipped',],\n            ['Sign Flip - Usual', 81],\n            ['Sign Flip - Minimal approach', 3792],\n            ['GG Flip (on low memory)', 5892],\n            ['GG Flip', 9792],\n          ]);\n          var options = {\n            chartArea: {width: '50%'},\n            hAxis: {\n              title: 'Signs Flipped per second',\n              minValue: 0\n            },\n            vAxis: {\n              title: 'Operation'\n            }\n          };\n          var chart = new google.visualization.BarChart(document.getElementById('chart_div'));\n          chart.draw(data, options);\n        }\n  </script>\n</body>\n</html>"
  },
  {
    "path": "main.go",
    "content": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"text/template\"\n)\n\nfunc main() {\n\n\tfuncMap := template.FuncMap{\n\t\t\"flip\": func(i int) string {\n\t\t\tif i == 0 {\n\t\t\t\treturn \"-0\"\n\t\t\t}\n\t\t\treturn fmt.Sprintf(\"%d\", ^i+1)\n\t\t},\n\t}\n\tf, err := os.Create(\"lib.js\")\n\tt := template.Must(template.New(\"template.txt\").Funcs(funcMap).ParseFiles(\"template.txt\"))\n\terr = t.Execute(f, make([]struct{}, 9007199254740992))\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}\n"
  },
  {
    "path": "template.txt",
    "content": "function signFlip(num) {\n    switch (num) {\n        {{ range $i, $e := . }}\n        case {{ $i }}:\n            return {{ flip $i }};\n\n        case {{ flip $i }}:\n            return {{ $i }};\n        {{ end }}\n        default:\n            return num-num*2;\n    }\n}"
  }
]