Full Code of avinassh/gg-flip for AI

master 996a8f3c68f5 cached
6 files
6.7 KB
1.8k tokens
1 symbols
1 requests
Download .txt
Repository: avinassh/gg-flip
Branch: master
Commit: 996a8f3c68f5
Files: 6
Total size: 6.7 KB

Directory structure:
gitextract_0451v6j8/

├── .gitignore
├── LICENSE
├── README.md
├── chart.html
├── main.go
└── template.txt

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so

# Folders
_obj
_test

# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out

*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*

_testmain.go

*.exe
*.test
*.prof


# Gogland IDE files
.idea/

# ENV variables/secrets
.envrc

# generated library file
lib.js

# binary
gg-flip

================================================
FILE: LICENSE
================================================
The MIT License (MIT)

Copyright (c) 2018 Avinash Sajjanshetty <hi@avi.im>

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


================================================
FILE: README.md
================================================
# GG Flip

Donald 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:

```javascript
x = 5
// get -5
x -= x*2;
```

Above 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:

![performance-report](perf.png)

But 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.

GG 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:

```
git clone https://github.com/avinassh/gg-flip.git
cd gg-flip
go run main.go
```

Above code generates highly readable file `lib.js`, which is:

```javascript
function signFlip(num) {
    switch (num) {
        case 0:
            return -0;
        case -0:
            return 0;
        case 1:
            return -1;
        case -1:
            return 1;
        // ...
        case 9:
            return -9;        
        case -9:
            return 9;
        // ...
        case 9007199254740991:
            return -9007199254740991;
        case -9007199254740991:
            return 9007199254740991;
        default:
            return num-num*2;
    }
}
```

Thanks 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:

![performance-report2](perf2.png)

Even 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.

The 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.

I 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.

## GG Flip as a Service

I 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.

## License

The mighty MIT license. Please check `LICENSE` for more details.


================================================
FILE: chart.html
================================================
<!DOCTYPE html>
<html>
<head>
  <title></title>
  <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
  <div id="chart_div"></div>
  <script type="text/javascript">
    google.charts.load('current', {packages: ['corechart', 'bar']});
    google.charts.setOnLoadCallback(drawBasic);

    function drawBasic() {
          var data = google.visualization.arrayToDataTable([
            ['Operation', 'Signs Flipped',],
            ['Sign Flip - Usual', 81],
            ['Sign Flip - Minimal approach', 3792],
            ['GG Flip (on low memory)', 5892],
            ['GG Flip', 9792],
          ]);
          var options = {
            chartArea: {width: '50%'},
            hAxis: {
              title: 'Signs Flipped per second',
              minValue: 0
            },
            vAxis: {
              title: 'Operation'
            }
          };
          var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
          chart.draw(data, options);
        }
  </script>
</body>
</html>

================================================
FILE: main.go
================================================
package main

import (
	"fmt"
	"log"
	"os"
	"text/template"
)

func main() {

	funcMap := template.FuncMap{
		"flip": func(i int) string {
			if i == 0 {
				return "-0"
			}
			return fmt.Sprintf("%d", ^i+1)
		},
	}
	f, err := os.Create("lib.js")
	t := template.Must(template.New("template.txt").Funcs(funcMap).ParseFiles("template.txt"))
	err = t.Execute(f, make([]struct{}, 9007199254740992))
	if err != nil {
		log.Fatalln(err)
	}
}


================================================
FILE: template.txt
================================================
function signFlip(num) {
    switch (num) {
        {{ range $i, $e := . }}
        case {{ $i }}:
            return {{ flip $i }};

        case {{ flip $i }}:
            return {{ $i }};
        {{ end }}
        default:
            return num-num*2;
    }
}
Download .txt
gitextract_0451v6j8/

├── .gitignore
├── LICENSE
├── README.md
├── chart.html
├── main.go
└── template.txt
Download .txt
SYMBOL INDEX (1 symbols across 1 files)

FILE: main.go
  function main (line 10) | func main() {
Condensed preview — 6 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (7K chars).
[
  {
    "path": ".gitignore",
    "chars": 377,
    "preview": "# 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 spe"
  },
  {
    "path": "LICENSE",
    "chars": 1099,
    "preview": "The MIT License (MIT)\n\nCopyright (c) 2018 Avinash Sajjanshetty <hi@avi.im>\n\nPermission is hereby granted, free of charge"
  },
  {
    "path": "README.md",
    "chars": 3645,
    "preview": "# GG Flip\n\nDonald Knuth described in one of his TAOCP books that flipping the sign of a number is one of the hardest pro"
  },
  {
    "path": "chart.html",
    "chars": 1076,
    "preview": "<!DOCTYPE html>\n<html>\n<head>\n  <title></title>\n  <script type=\"text/javascript\" src=\"https://www.gstatic.com/charts/loa"
  },
  {
    "path": "main.go",
    "chars": 437,
    "preview": "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\": fu"
  },
  {
    "path": "template.txt",
    "chars": 263,
    "preview": "function signFlip(num) {\n    switch (num) {\n        {{ range $i, $e := . }}\n        case {{ $i }}:\n            return {{"
  }
]

About this extraction

This page contains the full source code of the avinassh/gg-flip GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 6 files (6.7 KB), approximately 1.8k tokens, and a symbol index with 1 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!