everycode
everycode copied to clipboard
2014年11月26日
/*
* 读书那会,有木有给小伙伴们写纸条又怕被发现呢?
* 缴获纸条的老师,满心欢喜的查看你们小秘密的时候
* 发现是一堆乱码的表情会不会让你特爽
* 哈哈哈,想想都有点小激动呢。
* 那么问题来了:
* 声明一个构造函数构造一个加密器
* 根据传入的字符还有加密规则返回一个对象。
* 对象包含2个方法 `encode` 加密, `decode` 解密
* 如以下规则
* var abc = "abcdefghijklmnopqrstuvwxyz";
* var key = "keywordabcfghijlmnpqstuvxz";
* var cipher = new KeywordCipher(abc, key);
* cipher.encode("abc") //=> "key"
* cipher.encode("xyz") //=> "vxz"
* cipher.decode("key") //=> "abc"
* cipher.decode("vxz") //=> "xyz"
*/
function KeywordCipher(abc, keyword) {
this.encode = function (str) {
// ...
}
this.decode = function (str) {
// ...
}
}
NO ZUO NO DIE 23333333333.
function KeywordCipher(abc, keyword) {
this.encode = function(str, d) {
return str.split("").map(function(ch) {
return (ch = ((d ? keyword : abc).indexOf(ch))) === -1 ? "" : (d ? abc : keyword)[ch];
}).join("");
};
this.decode = function(str) {
return this.encode(str, 1);
};
}
function KeywordCipher(abc, keyword) {
_abc = abc.split('');
_keyword = keyword.split('');
this.encode = function (str) {
return str.split('').map(function(v, i) {return v = this[i]}, _keyword).join('');
}
this.decode = function (str) {
return str.split('').map(function(v, i) {return v = this[i]}, _abc).join('');
}
}
// 测试用例
var abc = "abcdefghijklmnopqrstuvwxyz";
var key = "keywordabcfghijlmnpqstuvxz";
var cipher = new KeywordCipher(abc, key);
console.log(cipher.encode("abc")); //=> "key"
console.log(cipher.decode("key")); //=> "abc"