randomWord.js 754 B

123456789101112131415161718192021222324252627282930313233
  1. /**
  2. * Created by Administrator on 2015/10/15.
  3. */
  4. module.exports = RandomWord;
  5. function RandomWord(chars){
  6. if(!(this instanceof RandomWord)){
  7. return new RandomWord(chars);
  8. }
  9. this._chars = "";
  10. if(chars){
  11. this.add(chars);
  12. }
  13. }
  14. RandomWord.prototype = {
  15. add:function(chars){
  16. this._chars += chars;
  17. return this;
  18. },
  19. random:function(size){
  20. var len = this._chars.length;
  21. if(len === 0){
  22. throw new Error('no chars,please use add(chars)');
  23. }
  24. var word = "";
  25. for(var i=0;i<size;i++){
  26. var cpo = parseInt(Math.random()*len);
  27. word += this._chars.charAt(cpo);
  28. }
  29. return word;
  30. }
  31. }