test-replace.nut 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. local str = "a day in life";
  2. print(str.replace("day", "night"));
  3. function my_find_close_quote(src, init=0){
  4. local src_size = str.len();
  5. if(init >= src_size) throw "invalid start position";
  6. for(; init < src_size; ++init) {
  7. if(src[init] == '"'){
  8. if(init < (src_size-1) && src[init+1] == '"') ++init; //skip quoted quote
  9. else break;
  10. }
  11. }
  12. if(src[init] != '"') init = -1;
  13. return init;
  14. }
  15. // Convert from CSV string to table
  16. function fromCSV (s){
  17. local t = []; // table to collect fields
  18. local fieldstart = 0;
  19. local slen = s.len();
  20. //local count = 0;
  21. do {
  22. //print("Count", ++count);
  23. // next field is quoted? (start with `"'?)
  24. if (s[fieldstart] == '"') {
  25. local i = s.find_close_quote(fieldstart+1);
  26. if (i<0) throw("unmatched \"");
  27. local f = s.slice(fieldstart+1, i);
  28. //print(f, f.replace("\"\"", "\""));
  29. t.push(f.replace("\"\"", "\""));
  30. local nextc = s.find(",", i);
  31. if(nextc < 0) nextc=slen-1;
  32. fieldstart = nextc + 1;
  33. }
  34. else // unquoted; find next comma
  35. {
  36. local nexti = s.find(",", fieldstart);
  37. if(nexti < 0) nexti = slen-1;
  38. //print("nn", fieldstart, nexti, s.slice(fieldstart, nexti))
  39. t.push(s.slice(fieldstart, nexti));
  40. fieldstart = nexti + 1;
  41. }
  42. } while(fieldstart < slen);
  43. if(s[slen-1] == ',') t.push("");
  44. return t;
  45. }
  46. str = "12,345.9,leon,,234.56,9,32,44444444444444444444444444444444444444444444444444444444444444444444444444444444444444,\"Domingo\"\",,\"tais\",leon,,234.56,9,32,44,\"laura\"";
  47. //str = [=[
  48. //"""ARTHUR BALFOUR"",CONSERVATIVE WORKING MEN'S CLUB LIMITED","IP10067R","","","","","","","","","Industrial and Provident Society","Active","United Kingdom","","01/01/1981","","","","","NO ACCOUNTS FILED","","","0","0","0","0","None Supplied","","","","0","0","http://business.data.gov.uk/id/company/IP10067R","","","","","","","","","","","","","","","","","","","",""]=];
  49. local ar2 = fromCSV(str);
  50. print(ar2.len());
  51. foreach(i, s in ar2) print(i,s);
  52. local ar
  53. local now = os.clock();
  54. for(local i=0; i< 100000; ++i){
  55. ar = fromCSV(str);
  56. }
  57. print("Spent", os.clock()-now)
  58. print(ar.len());
  59. foreach( i, s in ar) print(s);
  60. local pos;
  61. now = os.clock();
  62. for(local i=0; i< 100000; ++i){
  63. pos = str.find_close_quote();
  64. }
  65. print("Spent native", os.clock()-now)
  66. now = os.clock();
  67. for(local i=0; i< 100000; ++i){
  68. pos = my_find_close_quote(str);
  69. }
  70. print("Spent interpreted", os.clock()-now)
  71. os.exit();