2013-08-05 2 views

ответ

1

я нашел библиотеку RubyJs. Пожалуйста, проверь это.

http://rubyjs.org/

<script src="ruby.min.js"></script> 
<script> 
var str = R("aaa"); 
alert(str.next()); 
</script> 
4

A google search for "Ruby string succ Javascript" возвращает this gist from Devon Govett called "An implementation of Ruby's string.succ method in JavaScript" который, кажется, что вы после этого ...

/* 
* An implementation of Ruby's string.succ method. 
* By Devon Govett 
* 
* Returns the successor to str. The successor is calculated by incrementing characters starting 
* from the rightmost alphanumeric (or the rightmost character if there are no alphanumerics) in the 
* string. Incrementing a digit always results in another digit, and incrementing a letter results in 
* another letter of the same case. 
* 
* If the increment generates a carry, the character to the left of it is incremented. This 
* process repeats until there is no carry, adding an additional character if necessary. 
* 
* succ("abcd")  == "abce" 
* succ("THX1138") == "THX1139" 
* succ("<<koala>>") == "<<koalb>>" 
* succ("1999zzz") == "2000aaa" 
* succ("ZZZ9999") == "AAAA0000" 
*/ 

function succ(input) { 
    var alphabet = 'abcdefghijklmnopqrstuvwxyz', 
    length = alphabet.length, 
    result = input, 
    i = input.length; 

    while(i >= 0) { 
    var last = input.charAt(--i), 
     next = '', 
     carry = false; 

    if (isNaN(last)) { 
     index = alphabet.indexOf(last.toLowerCase()); 

     if (index === -1) { 
      next = last; 
      carry = true; 
     } 
     else { 
      var isUpperCase = last === last.toUpperCase(); 
      next = alphabet.charAt((index + 1) % length); 
      if (isUpperCase) { 
       next = next.toUpperCase(); 
      } 

      carry = index + 1 >= length; 
      if (carry && i === 0) { 
       var added = isUpperCase ? 'A' : 'a'; 
       result = added + next + result.slice(1); 
       break; 
      } 
     } 
    } 
    else { 
     next = +last + 1; 
     if(next > 9) { 
      next = 0; 
      carry = true 
     } 

     if (carry && i === 0) { 
      result = '1' + next + result.slice(1); 
      break; 
     } 
    } 

    result = result.slice(0, i) + next + result.slice(i + 1); 
    if (!carry) { 
     break; 
    } 
    } 
    return result; 
} 
+0

http://meta.stackexchange.com/a/15660 и http://meta.stackexchange.com/a/8259. –

+1

@JonathanLonowski Согласен с lmgtfy, поэтому я не указываю туда, но ссылаюсь на конкретные ключевые слова на Google, чтобы они могли читать дальше и считаться грубыми? Я так не думал. Что касается точки «только ссылка», да, справедливо, я был на своем телефоне и не собирался публиковать весь контент сущности. – Stobor

+0

@JonathanLonowski И я признаю, что я не так активен на мета, каким должен быть, и некоторое время не был в отъезде, а просто возвращался к ответу. – Stobor

0

Сочетание String.fromCharCode() и "".charCodeAt() должна быть достаточно прямолинейно реализовать.

var FIRST = 97, 
    LAST = 122; 

function next (string) { 
    var lastChar = string[string.length - 1]; 

    string = string.substring(0, string.length - 1); 

    if(lastChar.charCodeAt(0) >= LAST) { 
    // make last char a and append a 
    lastChar = String.fromCharCode(FIRST) + String.fromCharCode(FIRST); 
    } 
    else { 
    // Increase last char 
    lastChar = String.fromCharCode(lastChar.charCodeAt(0) + 1); 
    } 

    return string + lastChar; 
} 

Очень быстрый и грязный и ведет себя немного странно (ZZZ -> zzaa вместо zaaa или zzza, не уверен, что поведение лучше всего), но он показывает, как вы могли бы идти о реализации его (и атм у меня нет времени, чтобы написать более изысканный ответ).

Смежные вопросы