Advertisement
Guest User

Untitled

a guest
Jul 4th, 2015
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. export let re2 = /^(?:([-+]?(?:\d+|\d+\.\d+))\s*,\s*)?([-+]?(?:\d+|\d+\.\d+))(?:\s*\.\.(\.?)\s*([-+]?(?:\d+|\d+\.\d+)))?$/;
  2. export let re = /^([-+]?(?:\d+|\d+\.\d+))(?:\s*,\s*([-+]?(?:\d+|\d+\.\d+)))?(?:\s*(\.\.\.?)\s*([-+]?(?:\d+|\d+\.\d+)))?$/;
  3.  
  4.  
  5. function toArray(value) {
  6. if (Array.isArray(value)) {
  7. return value.slice();
  8. }
  9. if (typeof value !== "string") {
  10. return [ value ];
  11. }
  12.  
  13. var matched = re.exec(value.trim());
  14.  
  15. if (!matched) {
  16. return [];
  17. }
  18.  
  19. let [ _, first, second, dots, last ] = matched;
  20.  
  21. first = +first;
  22.  
  23. if (typeof last === "undefined") {
  24. return [ first ];
  25. }
  26.  
  27. last = +last;
  28.  
  29. let a = [];
  30. let step = (typeof second !== "undefined") ? (+second - first) : (first < last) ? 1 : -1;
  31.  
  32. // console.log(first, step, last);
  33.  
  34. let x = first;
  35.  
  36. if (dots === "...") {
  37. if (0 < step) {
  38. while (x < last) {
  39. a.push(x);
  40. x += step;
  41. }
  42. } else if (step < 0) {
  43. while (x > last) {
  44. a.push(x);
  45. x += step;
  46. }
  47. }
  48. } else {
  49. if (0 < step) {
  50. while (x <= last) {
  51. a.push(x);
  52. x += step;
  53. }
  54. } else if (step < 0) {
  55. while (x >= last) {
  56. a.push(x);
  57. x += step;
  58. }
  59. }
  60. }
  61.  
  62. return a;
  63. }
  64.  
  65.  
  66. function test(str) {
  67. let result = toArray(str);
  68.  
  69. console.log(str, result);
  70.  
  71. // let matched = re.exec(str);
  72. //
  73. // if (!matched) {
  74. // return;
  75. // }
  76. //
  77. // let [ _, first, second, dots, last ] = matched;
  78. //
  79. // console.log(`first: ${first}`);
  80. // console.log(`second: ${second}`);
  81. // console.log(`last: ${last}`);
  82. // console.log(`dots: ${dots}`);
  83. // console.log("=======================");
  84. }
  85.  
  86. test("1");
  87. test("1..20");
  88. test("1...20");
  89. test("0, 2..20");
  90. test("0, 2...20");
  91. test("0, -2..20");
  92. test("0, 0..20");
  93. test("0, 1");
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement