Full Code of leongersen/wnumb for AI

master 740c52102acd cached
7 files
16.3 KB
4.8k tokens
11 symbols
1 requests
Download .txt
Repository: leongersen/wnumb
Branch: master
Commit: 740c52102acd
Files: 7
Total size: 16.3 KB

Directory structure:
gitextract_gzzcwu6t/

├── .gitignore
├── LICENSE.MD
├── README.md
├── bower.json
├── package.json
├── test.html
└── wNumb.js

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

================================================
FILE: .gitignore
================================================
/node_modules


================================================
FILE: LICENSE.MD
================================================
MIT License

Copyright (c) 2019 Léon Gersen

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
================================================
wNumb
=====

wNumb - JavaScript Number & Money formatting

# Documentation

Documentation and examples are available on [refreshless.com/wnumb](https://refreshless.com/wnumb/).

# Changelog

### 1.2.0 (*2019-10-29*)
- Changed: License is now MIT
- Added: Prettier code formatter
- Added: Minified version

### 1.1.0 (*2017-02-04*)
- Changed: Renamed `postfix` option to the proper `suffix`. `postfix` is remapped internally for backward compatibility;

# License

Licensed MIT, so free for personal and commercial use.


================================================
FILE: bower.json
================================================
{
  "name": "wnumb",
  "main": "wNumb.js",
  "version": "1.1.0",
  "homepage": "https://refreshless.com/wnumb/",
  "description": "wNumb - JavaScript Number & Money formatting",
  "keywords": [
    "javascript",
    "js",
    "number",
    "money",
    "formatting"
  ],
  "authors": [
    "Leon Gersen"
  ],
  "license": "WTFPL",
  "ignore": [
    "**/.*",
    "node_modules",
    "bower_components",
    "test",
    "tests"
  ]
}


================================================
FILE: package.json
================================================
{
  "name": "wnumb",
  "version": "1.2.0",
  "description": "wNumb - JavaScript Number & Money formatting",
  "main": "wNumb.js",
  "repository": {
    "type": "git",
    "url": "git://github.com/leongersen/wnumb.git"
  },
  "author": "leongersen",
  "license": "MIT",
  "scripts": {
    "format": "prettier wNumb.js --write --print-width=120",
    "minify": "uglifyjs wNumb.js --compress --mangle --output wNumb.min.js",
    "build": "npm run format && npm run minify"
  },
  "files": [
    "wNumb.js",
    "wNumb.min.js"
  ],
  "bugs": {
    "url": "https://github.com/leongersen/wnumb/issues"
  },
  "devDependencies": {
    "prettier": "^1.18.2",
    "uglify-js": "^3.6.5"
  }
}


================================================
FILE: test.html
================================================
<!DOCTYPE html>

	<head>
		<link href="http://code.jquery.com/qunit/qunit-1.12.0.css" rel="stylesheet">
		<script src="http://code.jquery.com/qunit/qunit-1.12.0.js"></script>
		<script src="wNumb.min.js"></script>
	</head>

	<div id="qunit"></div>

	<script>

		test( "Testing mark, thousand, decimals", function(){

			var Tester = wNumb({
				mark: '_',
				thousand: '?',
				decimals: 3
			});

			equal ( Tester.to ( 9129 ), '9?129_000' );
			equal ( Tester.from ( '9?129_000' ), 9129 );

			equal ( Tester.to ( 100000000000.99999999 ), '100?000?000?001_000' );
			equal ( Tester.from ( '100?000?000?001_000' ), 100000000000.99999999 );

			equal ( Tester.to ( 7 ), '7_000' );
			equal ( Tester.from ( '7_000' ), 7 );

			equal ( Tester.to ( 'q' ), false );

			equal ( Tester.to ( 8000.001 ), '8?000_001' );
			equal ( Tester.from ( '8?000_001' ), 8000.001 );

			equal ( Tester.to ( -700 ), '-700_000' );
			equal ( Tester.from ( '-700_000' ), -700.000 );

			equal ( Tester.to ( -79900.0405 ), '-79?900_041' );
			equal ( Tester.from ( '-79?900_041' ), -79900.041 );
		});

		test( "Testing 0 decimals", function(){

			var Tester = wNumb({
				decimals: 0
			});

			equal ( Tester.to ( -50.999845 ), '-51' );
			equal ( Tester.to ( -0.0000001 ), '0' );
		});

		test( "Testing rounding", function(){

			var Tester = wNumb({
				decimals: 2
			});

			equal ( Tester.to ( 8.905 ), '8.91' );
			equal ( Tester.to ( 8.9049999 ), '8.90' );
			equal ( Tester.to ( 8.9045 ), '8.90' );
			equal ( Tester.to ( 8.9044 ), '8.90' );
			equal ( Tester.to ( 8.9 ), '8.90' );
			equal ( Tester.to ( 1.275 ), '1.28' );
			equal ( Tester.to ( 1.27499 ), '1.27' );
		});

		test( "Testing mark and thousand with longer strings", function(){

			var Tester = wNumb({
				mark: '/**',
				thousand: '-+A',
				decimals: 2
			});

			equal ( Tester.to ( 450 ), '450/**00' );
			equal ( Tester.from ( '450/**00' ), 450.00 );

			equal ( Tester.to ( 80000 ), '80-+A000/**00' );
			equal ( Tester.from ( '80-+A000/**00' ), 80000 );

		});

		test( "Testing prefix and suffix", function(){

			var Tester = wNumb({
				prefix: '$',
				suffix: ' p.p.',
				decimals: 5
			});

			equal ( Tester.to ( 230.089044 ), '$230.08904 p.p.' );
			equal ( Tester.from ( '$230.08904 p.p.' ), 230.08904 );

			equal ( Tester.to ( 1 ), '$1.00000 p.p.' );
			equal ( Tester.from ( '$1.00000 p.p.' ), 1.00000 );

			equal ( Tester.to ( 16.5 ), '$16.50000 p.p.' );

			equal ( Tester.from ( '$1500' ), 1500 );
			equal ( Tester.from ( '1500' ), 1500 );
			equal ( Tester.from ( '1500 p.p.' ), 1500 );
			equal ( Tester.from ( '1500 ' ), 1500 );
			equal ( Tester.from ( '  1500 ' ), 1500 );
			equal ( Tester.from ( ' 1.50.0 ' ), false );

			var Tester2 = wNumb({
				postfix: ' postfix!',
				decimals: 1
			});

			equal ( Tester2.to ( 1 ), '1.0 postfix!' );
		});

		test( "Testing prefix and with negativeBefore", function(){

			var Tester = wNumb({
				prefix: '$',
				negativeBefore: '[NEGATIVE] '
			});

			equal ( Tester.to ( 260 ), '$260' );
			equal ( Tester.from ( '$260' ), 260 );

			equal ( Tester.to ( -260 ), '[NEGATIVE] $260' );
			equal ( Tester.from ( '[NEGATIVE] $260' ), -260 );

		});

		test( "Testing prefix and with negative", function(){

			var Tester = wNumb({
				prefix: 'Price: '
			});

			equal ( Tester.to ( 380.6 ), 'Price: 380.6' );
			equal ( Tester.from ( 'Price: 380.6' ), 380.6 );

			equal ( Tester.to ( -9506 ), 'Price: -9506' );
			equal ( Tester.from ( 'Price: -9506' ), -9506 );

		});

		test( "Testing encoder, decoder", function(){

			var Tester = wNumb({
				thousand: '.',
				encoder: function( a ){
					return a * 1E7;
				},
				decoder: function( a ){
					return a / 1E7;
				}
			});

			equal ( Tester.to ( 10 ), '100.000.000' );
			equal ( Tester.from ( '100.000.000' ), 10 );

			equal ( Tester.to ( -9506 ), '-95.060.000.000' );
			equal ( Tester.from ( '-95.060.000.000' ), -9506 );

		});

		test( "Testing edit, undo", function(){

			var Tester = wNumb({
				edit: function( value, originalValue ){
					if ( originalValue > 100000 ) {
						return value + 'm';
					} else if ( originalValue > 1000 ) {
						return value + 'k';
					} else {
						return value;
					}
				},
				undo: function( value ){
					return value;
				}
			});

			equal ( Tester.to ( 15000 ), '15000k' );
			equal ( Tester.from ( '15000k' ), 15000 );

			equal ( Tester.to ( 180 ), '180' );
			equal ( Tester.from ( '180' ), 180 );

			equal ( Tester.to ( 1058009 ), '1058009m' );
		});

	</script>


================================================
FILE: wNumb.js
================================================
(function(factory) {
  if (typeof define === "function" && define.amd) {
    // AMD. Register as an anonymous module.
    define([], factory);
  } else if (typeof exports === "object") {
    // Node/CommonJS
    module.exports = factory();
  } else {
    // Browser globals
    window.wNumb = factory();
  }
})(function() {
  "use strict";

  var FormatOptions = [
    "decimals",
    "thousand",
    "mark",
    "prefix",
    "suffix",
    "encoder",
    "decoder",
    "negativeBefore",
    "negative",
    "edit",
    "undo"
  ];

  // General

  // Reverse a string
  function strReverse(a) {
    return a
      .split("")
      .reverse()
      .join("");
  }

  // Check if a string starts with a specified prefix.
  function strStartsWith(input, match) {
    return input.substring(0, match.length) === match;
  }

  // Check is a string ends in a specified suffix.
  function strEndsWith(input, match) {
    return input.slice(-1 * match.length) === match;
  }

  // Throw an error if formatting options are incompatible.
  function throwEqualError(F, a, b) {
    if ((F[a] || F[b]) && F[a] === F[b]) {
      throw new Error(a);
    }
  }

  // Check if a number is finite and not NaN
  function isValidNumber(input) {
    return typeof input === "number" && isFinite(input);
  }

  // Provide rounding-accurate toFixed method.
  // Borrowed: http://stackoverflow.com/a/21323330/775265
  function toFixed(value, exp) {
    value = value.toString().split("e");
    value = Math.round(+(value[0] + "e" + (value[1] ? +value[1] + exp : exp)));
    value = value.toString().split("e");
    return (+(value[0] + "e" + (value[1] ? +value[1] - exp : -exp))).toFixed(exp);
  }

  // Formatting

  // Accept a number as input, output formatted string.
  function formatTo(
    decimals,
    thousand,
    mark,
    prefix,
    suffix,
    encoder,
    decoder,
    negativeBefore,
    negative,
    edit,
    undo,
    input
  ) {
    var originalInput = input,
      inputIsNegative,
      inputPieces,
      inputBase,
      inputDecimals = "",
      output = "";

    // Apply user encoder to the input.
    // Expected outcome: number.
    if (encoder) {
      input = encoder(input);
    }

    // Stop if no valid number was provided, the number is infinite or NaN.
    if (!isValidNumber(input)) {
      return false;
    }

    // Rounding away decimals might cause a value of -0
    // when using very small ranges. Remove those cases.
    if (decimals !== false && parseFloat(input.toFixed(decimals)) === 0) {
      input = 0;
    }

    // Formatting is done on absolute numbers,
    // decorated by an optional negative symbol.
    if (input < 0) {
      inputIsNegative = true;
      input = Math.abs(input);
    }

    // Reduce the number of decimals to the specified option.
    if (decimals !== false) {
      input = toFixed(input, decimals);
    }

    // Transform the number into a string, so it can be split.
    input = input.toString();

    // Break the number on the decimal separator.
    if (input.indexOf(".") !== -1) {
      inputPieces = input.split(".");

      inputBase = inputPieces[0];

      if (mark) {
        inputDecimals = mark + inputPieces[1];
      }
    } else {
      // If it isn't split, the entire number will do.
      inputBase = input;
    }

    // Group numbers in sets of three.
    if (thousand) {
      inputBase = strReverse(inputBase).match(/.{1,3}/g);
      inputBase = strReverse(inputBase.join(strReverse(thousand)));
    }

    // If the number is negative, prefix with negation symbol.
    if (inputIsNegative && negativeBefore) {
      output += negativeBefore;
    }

    // Prefix the number
    if (prefix) {
      output += prefix;
    }

    // Normal negative option comes after the prefix. Defaults to '-'.
    if (inputIsNegative && negative) {
      output += negative;
    }

    // Append the actual number.
    output += inputBase;
    output += inputDecimals;

    // Apply the suffix.
    if (suffix) {
      output += suffix;
    }

    // Run the output through a user-specified post-formatter.
    if (edit) {
      output = edit(output, originalInput);
    }

    // All done.
    return output;
  }

  // Accept a sting as input, output decoded number.
  function formatFrom(
    decimals,
    thousand,
    mark,
    prefix,
    suffix,
    encoder,
    decoder,
    negativeBefore,
    negative,
    edit,
    undo,
    input
  ) {
    var originalInput = input,
      inputIsNegative,
      output = "";

    // User defined pre-decoder. Result must be a non empty string.
    if (undo) {
      input = undo(input);
    }

    // Test the input. Can't be empty.
    if (!input || typeof input !== "string") {
      return false;
    }

    // If the string starts with the negativeBefore value: remove it.
    // Remember is was there, the number is negative.
    if (negativeBefore && strStartsWith(input, negativeBefore)) {
      input = input.replace(negativeBefore, "");
      inputIsNegative = true;
    }

    // Repeat the same procedure for the prefix.
    if (prefix && strStartsWith(input, prefix)) {
      input = input.replace(prefix, "");
    }

    // And again for negative.
    if (negative && strStartsWith(input, negative)) {
      input = input.replace(negative, "");
      inputIsNegative = true;
    }

    // Remove the suffix.
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice
    if (suffix && strEndsWith(input, suffix)) {
      input = input.slice(0, -1 * suffix.length);
    }

    // Remove the thousand grouping.
    if (thousand) {
      input = input.split(thousand).join("");
    }

    // Set the decimal separator back to period.
    if (mark) {
      input = input.replace(mark, ".");
    }

    // Prepend the negative symbol.
    if (inputIsNegative) {
      output += "-";
    }

    // Add the number
    output += input;

    // Trim all non-numeric characters (allow '.' and '-');
    output = output.replace(/[^0-9\.\-.]/g, "");

    // The value contains no parse-able number.
    if (output === "") {
      return false;
    }

    // Covert to number.
    output = Number(output);

    // Run the user-specified post-decoder.
    if (decoder) {
      output = decoder(output);
    }

    // Check is the output is valid, otherwise: return false.
    if (!isValidNumber(output)) {
      return false;
    }

    return output;
  }

  // Framework

  // Validate formatting options
  function validate(inputOptions) {
    var i,
      optionName,
      optionValue,
      filteredOptions = {};

    if (inputOptions["suffix"] === undefined) {
      inputOptions["suffix"] = inputOptions["postfix"];
    }

    for (i = 0; i < FormatOptions.length; i += 1) {
      optionName = FormatOptions[i];
      optionValue = inputOptions[optionName];

      if (optionValue === undefined) {
        // Only default if negativeBefore isn't set.
        if (optionName === "negative" && !filteredOptions.negativeBefore) {
          filteredOptions[optionName] = "-";
          // Don't set a default for mark when 'thousand' is set.
        } else if (optionName === "mark" && filteredOptions.thousand !== ".") {
          filteredOptions[optionName] = ".";
        } else {
          filteredOptions[optionName] = false;
        }

        // Floating points in JS are stable up to 7 decimals.
      } else if (optionName === "decimals") {
        if (optionValue >= 0 && optionValue < 8) {
          filteredOptions[optionName] = optionValue;
        } else {
          throw new Error(optionName);
        }

        // These options, when provided, must be functions.
      } else if (
        optionName === "encoder" ||
        optionName === "decoder" ||
        optionName === "edit" ||
        optionName === "undo"
      ) {
        if (typeof optionValue === "function") {
          filteredOptions[optionName] = optionValue;
        } else {
          throw new Error(optionName);
        }

        // Other options are strings.
      } else {
        if (typeof optionValue === "string") {
          filteredOptions[optionName] = optionValue;
        } else {
          throw new Error(optionName);
        }
      }
    }

    // Some values can't be extracted from a
    // string if certain combinations are present.
    throwEqualError(filteredOptions, "mark", "thousand");
    throwEqualError(filteredOptions, "prefix", "negative");
    throwEqualError(filteredOptions, "prefix", "negativeBefore");

    return filteredOptions;
  }

  // Pass all options as function arguments
  function passAll(options, method, input) {
    var i,
      args = [];

    // Add all options in order of FormatOptions
    for (i = 0; i < FormatOptions.length; i += 1) {
      args.push(options[FormatOptions[i]]);
    }

    // Append the input, then call the method, presenting all
    // options as arguments.
    args.push(input);
    return method.apply("", args);
  }

  function wNumb(options) {
    if (!(this instanceof wNumb)) {
      return new wNumb(options);
    }

    if (typeof options !== "object") {
      return;
    }

    options = validate(options);

    // Call 'formatTo' with proper arguments.
    this.to = function(input) {
      return passAll(options, formatTo, input);
    };

    // Call 'formatFrom' with proper arguments.
    this.from = function(input) {
      return passAll(options, formatFrom, input);
    };
  }

  return wNumb;
});
Download .txt
gitextract_gzzcwu6t/

├── .gitignore
├── LICENSE.MD
├── README.md
├── bower.json
├── package.json
├── test.html
└── wNumb.js
Download .txt
SYMBOL INDEX (11 symbols across 1 files)

FILE: wNumb.js
  function strReverse (line 32) | function strReverse(a) {
  function strStartsWith (line 40) | function strStartsWith(input, match) {
  function strEndsWith (line 45) | function strEndsWith(input, match) {
  function throwEqualError (line 50) | function throwEqualError(F, a, b) {
  function isValidNumber (line 57) | function isValidNumber(input) {
  function toFixed (line 63) | function toFixed(value, exp) {
  function formatTo (line 73) | function formatTo(
  function formatFrom (line 180) | function formatFrom(
  function validate (line 277) | function validate(inputOptions) {
  function passAll (line 343) | function passAll(options, method, input) {
  function wNumb (line 358) | function wNumb(options) {
Condensed preview — 7 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (18K chars).
[
  {
    "path": ".gitignore",
    "chars": 14,
    "preview": "/node_modules\n"
  },
  {
    "path": "LICENSE.MD",
    "chars": 1068,
    "preview": "MIT License\n\nCopyright (c) 2019 Léon Gersen\n\nPermission is hereby granted, free of charge, to any person obtaining a cop"
  },
  {
    "path": "README.md",
    "chars": 523,
    "preview": "wNumb\n=====\n\nwNumb - JavaScript Number &amp; Money formatting\n\n# Documentation\n\nDocumentation and examples are available"
  },
  {
    "path": "bower.json",
    "chars": 432,
    "preview": "{\n  \"name\": \"wnumb\",\n  \"main\": \"wNumb.js\",\n  \"version\": \"1.1.0\",\n  \"homepage\": \"https://refreshless.com/wnumb/\",\n  \"desc"
  },
  {
    "path": "package.json",
    "chars": 683,
    "preview": "{\n  \"name\": \"wnumb\",\n  \"version\": \"1.2.0\",\n  \"description\": \"wNumb - JavaScript Number & Money formatting\",\n  \"main\": \"w"
  },
  {
    "path": "test.html",
    "chars": 4519,
    "preview": "<!DOCTYPE html>\n\n\t<head>\n\t\t<link href=\"http://code.jquery.com/qunit/qunit-1.12.0.css\" rel=\"stylesheet\">\n\t\t<script src=\"h"
  },
  {
    "path": "wNumb.js",
    "chars": 9439,
    "preview": "(function(factory) {\n  if (typeof define === \"function\" && define.amd) {\n    // AMD. Register as an anonymous module.\n  "
  }
]

About this extraction

This page contains the full source code of the leongersen/wnumb GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 7 files (16.3 KB), approximately 4.8k tokens, and a symbol index with 11 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!