wNumb.js 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. (function (factory) {
  2. if ( typeof define === 'function' && define.amd ) {
  3. // AMD. Register as an anonymous module.
  4. define([], factory);
  5. } else if ( typeof exports === 'object' ) {
  6. // Node/CommonJS
  7. module.exports = factory();
  8. } else {
  9. // Browser globals
  10. window.wNumb = factory();
  11. }
  12. }(function(){
  13. 'use strict';
  14. var
  15. /** @const */ FormatOptions = [
  16. 'decimals',
  17. 'thousand',
  18. 'mark',
  19. 'prefix',
  20. 'postfix',
  21. 'encoder',
  22. 'decoder',
  23. 'negativeBefore',
  24. 'negative',
  25. 'edit',
  26. 'undo'
  27. ];
  28. // General
  29. // Reverse a string
  30. function strReverse ( a ) {
  31. return a.split('').reverse().join('');
  32. }
  33. // Check if a string starts with a specified prefix.
  34. function strStartsWith ( input, match ) {
  35. return input.substring(0, match.length) === match;
  36. }
  37. // Check is a string ends in a specified postfix.
  38. function strEndsWith ( input, match ) {
  39. return input.slice(-1 * match.length) === match;
  40. }
  41. // Throw an error if formatting options are incompatible.
  42. function throwEqualError( F, a, b ) {
  43. if ( (F[a] || F[b]) && (F[a] === F[b]) ) {
  44. throw new Error(a);
  45. }
  46. }
  47. // Check if a number is finite and not NaN
  48. function isValidNumber ( input ) {
  49. return typeof input === 'number' && isFinite( input );
  50. }
  51. // Provide rounding-accurate toFixed method.
  52. function toFixed ( value, decimals ) {
  53. var scale = Math.pow(10, decimals);
  54. return ( Math.round(value * scale) / scale).toFixed( decimals );
  55. }
  56. // Formatting
  57. // Accept a number as input, output formatted string.
  58. function formatTo ( decimals, thousand, mark, prefix, postfix, encoder, decoder, negativeBefore, negative, edit, undo, input ) {
  59. var originalInput = input, inputIsNegative, inputPieces, inputBase, inputDecimals = '', output = '';
  60. // Apply user encoder to the input.
  61. // Expected outcome: number.
  62. if ( encoder ) {
  63. input = encoder(input);
  64. }
  65. // Stop if no valid number was provided, the number is infinite or NaN.
  66. if ( !isValidNumber(input) ) {
  67. return false;
  68. }
  69. // Rounding away decimals might cause a value of -0
  70. // when using very small ranges. Remove those cases.
  71. if ( decimals !== false && parseFloat(input.toFixed(decimals)) === 0 ) {
  72. input = 0;
  73. }
  74. // Formatting is done on absolute numbers,
  75. // decorated by an optional negative symbol.
  76. if ( input < 0 ) {
  77. inputIsNegative = true;
  78. input = Math.abs(input);
  79. }
  80. // Reduce the number of decimals to the specified option.
  81. if ( decimals !== false ) {
  82. input = toFixed( input, decimals );
  83. }
  84. // Transform the number into a string, so it can be split.
  85. input = input.toString();
  86. // Break the number on the decimal separator.
  87. if ( input.indexOf('.') !== -1 ) {
  88. inputPieces = input.split('.');
  89. inputBase = inputPieces[0];
  90. if ( mark ) {
  91. inputDecimals = mark + inputPieces[1];
  92. }
  93. } else {
  94. // If it isn't split, the entire number will do.
  95. inputBase = input;
  96. }
  97. // Group numbers in sets of three.
  98. if ( thousand ) {
  99. inputBase = strReverse(inputBase).match(/.{1,3}/g);
  100. inputBase = strReverse(inputBase.join( strReverse( thousand ) ));
  101. }
  102. // If the number is negative, prefix with negation symbol.
  103. if ( inputIsNegative && negativeBefore ) {
  104. output += negativeBefore;
  105. }
  106. // Prefix the number
  107. if ( prefix ) {
  108. output += prefix;
  109. }
  110. // Normal negative option comes after the prefix. Defaults to '-'.
  111. if ( inputIsNegative && negative ) {
  112. output += negative;
  113. }
  114. // Append the actual number.
  115. output += inputBase;
  116. output += inputDecimals;
  117. // Apply the postfix.
  118. if ( postfix ) {
  119. output += postfix;
  120. }
  121. // Run the output through a user-specified post-formatter.
  122. if ( edit ) {
  123. output = edit ( output, originalInput );
  124. }
  125. // All done.
  126. return output;
  127. }
  128. // Accept a sting as input, output decoded number.
  129. function formatFrom ( decimals, thousand, mark, prefix, postfix, encoder, decoder, negativeBefore, negative, edit, undo, input ) {
  130. var originalInput = input, inputIsNegative, output = '';
  131. // User defined pre-decoder. Result must be a non empty string.
  132. if ( undo ) {
  133. input = undo(input);
  134. }
  135. // Test the input. Can't be empty.
  136. if ( !input || typeof input !== 'string' ) {
  137. return false;
  138. }
  139. // If the string starts with the negativeBefore value: remove it.
  140. // Remember is was there, the number is negative.
  141. if ( negativeBefore && strStartsWith(input, negativeBefore) ) {
  142. input = input.replace(negativeBefore, '');
  143. inputIsNegative = true;
  144. }
  145. // Repeat the same procedure for the prefix.
  146. if ( prefix && strStartsWith(input, prefix) ) {
  147. input = input.replace(prefix, '');
  148. }
  149. // And again for negative.
  150. if ( negative && strStartsWith(input, negative) ) {
  151. input = input.replace(negative, '');
  152. inputIsNegative = true;
  153. }
  154. // Remove the postfix.
  155. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice
  156. if ( postfix && strEndsWith(input, postfix) ) {
  157. input = input.slice(0, -1 * postfix.length);
  158. }
  159. // Remove the thousand grouping.
  160. if ( thousand ) {
  161. input = input.split(thousand).join('');
  162. }
  163. // Set the decimal separator back to period.
  164. if ( mark ) {
  165. input = input.replace(mark, '.');
  166. }
  167. // Prepend the negative symbol.
  168. if ( inputIsNegative ) {
  169. output += '-';
  170. }
  171. // Add the number
  172. output += input;
  173. // Trim all non-numeric characters (allow '.' and '-');
  174. output = output.replace(/[^0-9\.\-.]/g, '');
  175. // The value contains no parse-able number.
  176. if ( output === '' ) {
  177. return false;
  178. }
  179. // Covert to number.
  180. output = Number(output);
  181. // Run the user-specified post-decoder.
  182. if ( decoder ) {
  183. output = decoder(output);
  184. }
  185. // Check is the output is valid, otherwise: return false.
  186. if ( !isValidNumber(output) ) {
  187. return false;
  188. }
  189. return output;
  190. }
  191. // Framework
  192. // Validate formatting options
  193. function validate ( inputOptions ) {
  194. var i, optionName, optionValue,
  195. filteredOptions = {};
  196. for ( i = 0; i < FormatOptions.length; i+=1 ) {
  197. optionName = FormatOptions[i];
  198. optionValue = inputOptions[optionName];
  199. if ( optionValue === undefined ) {
  200. // Only default if negativeBefore isn't set.
  201. if ( optionName === 'negative' && !filteredOptions.negativeBefore ) {
  202. filteredOptions[optionName] = '-';
  203. // Don't set a default for mark when 'thousand' is set.
  204. } else if ( optionName === 'mark' && filteredOptions.thousand !== '.' ) {
  205. filteredOptions[optionName] = '.';
  206. } else {
  207. filteredOptions[optionName] = false;
  208. }
  209. // Floating points in JS are stable up to 7 decimals.
  210. } else if ( optionName === 'decimals' ) {
  211. if ( optionValue >= 0 && optionValue < 8 ) {
  212. filteredOptions[optionName] = optionValue;
  213. } else {
  214. throw new Error(optionName);
  215. }
  216. // These options, when provided, must be functions.
  217. } else if ( optionName === 'encoder' || optionName === 'decoder' || optionName === 'edit' || optionName === 'undo' ) {
  218. if ( typeof optionValue === 'function' ) {
  219. filteredOptions[optionName] = optionValue;
  220. } else {
  221. throw new Error(optionName);
  222. }
  223. // Other options are strings.
  224. } else {
  225. if ( typeof optionValue === 'string' ) {
  226. filteredOptions[optionName] = optionValue;
  227. } else {
  228. throw new Error(optionName);
  229. }
  230. }
  231. }
  232. // Some values can't be extracted from a
  233. // string if certain combinations are present.
  234. throwEqualError(filteredOptions, 'mark', 'thousand');
  235. throwEqualError(filteredOptions, 'prefix', 'negative');
  236. throwEqualError(filteredOptions, 'prefix', 'negativeBefore');
  237. return filteredOptions;
  238. }
  239. // Pass all options as function arguments
  240. function passAll ( options, method, input ) {
  241. var i, args = [];
  242. // Add all options in order of FormatOptions
  243. for ( i = 0; i < FormatOptions.length; i+=1 ) {
  244. args.push(options[FormatOptions[i]]);
  245. }
  246. // Append the input, then call the method, presenting all
  247. // options as arguments.
  248. args.push(input);
  249. return method.apply('', args);
  250. }
  251. /** @constructor */
  252. function wNumb ( options ) {
  253. if ( !(this instanceof wNumb) ) {
  254. return new wNumb ( options );
  255. }
  256. if ( typeof options !== "object" ) {
  257. return;
  258. }
  259. options = validate(options);
  260. // Call 'formatTo' with proper arguments.
  261. this.to = function ( input ) {
  262. return passAll(options, formatTo, input);
  263. };
  264. // Call 'formatFrom' with proper arguments.
  265. this.from = function ( input ) {
  266. return passAll(options, formatFrom, input);
  267. };
  268. }
  269. /** @export */
  270. return wNumb;
  271. }));