Created
September 9, 2021 06:10
-
-
Save consatan/a593eebbde77a4a2a42697b242da2156 to your computer and use it in GitHub Desktop.
php strtr 函数的 js 实现,用于实现简单的自定义编码,如 自定义 base64 编码
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// php strtr 函数的 js 实现 v.a. https://www.php.net/manual/en/function.strtr.php | |
// 只实现了 strtr(string $str, array $replace_pairs) 这种调用方法,且 replace_pairs 里只能是单个字符替换为单个字符 | |
// 目的是为了做凯撒密码实现 | |
String.prototype.strtr = function(dic) { | |
return this.toString().split('').map(char => dic[char] || char).join(''); | |
} | |
// 调用 | |
let str = '123321123'; | |
console.log(str.strtr({'1': 2, '2': 3, '3': 1})); // 231132231 | |
// 打乱数组顺序 | |
// v.a. https://stackoverflow.com/a/2450976/831243 | |
function shuffle(origArr) { | |
var array = origArr.concat([]); // get array copy | |
var currentIndex = array.length, randomIndex; | |
// While there remain elements to shuffle... | |
while (currentIndex != 0) { | |
// Pick a remaining element... | |
randomIndex = Math.floor(Math.random() * currentIndex); | |
currentIndex--; | |
// And swap it with the current element. | |
[array[currentIndex], array[randomIndex]] = [ | |
array[randomIndex], array[currentIndex]]; | |
} | |
return array; | |
} | |
// 自定义 base64 编码 | |
const defaultTab = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); | |
const customTab = shuffle(defaultTab); | |
console.log(customTab.join('')); // 打印自定义编码 | |
let dic = {}; | |
defaultTab.map((val, idx) => dic[val] = customTab[idx]); | |
console.log(dic); // 打印密码表 | |
let str = 'aGVsbG8gd29ybGQ='; // base64_encode('hello world'); | |
let customStr = str.strtr(dic); | |
console.log(customStr); | |
// 还原为标准 base64 编码 | |
let flip = {} | |
Object.keys(dic).forEach(key => flip[dic[key]] = key); | |
console.log(customStr.strtr(flip) === str); // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment