Skip to content

Instantly share code, notes, and snippets.

@st98
Last active December 30, 2015 08:09
Show Gist options
  • Save st98/7800799 to your computer and use it in GitHub Desktop.
Save st98/7800799 to your computer and use it in GitHub Desktop.
ascii.encode('hoge') === '686f6765';
(function () {
'use strict';
var root = this;
var ascii = {};
var prevAscii = root.ascii;
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = ascii;
}
exports.ascii = ascii;
} else {
root.ascii = ascii;
}
var chars = function (str) {
return str.split('');
};
var reverse = function (str) {
return chars(str).reverse().join('');
};
var partition = function (str, n) {
var regex = '(.{' + n + '})|(.+)';
return str.match(new RegExp(regex, 'g'));
};
var rpartition = function (str, n) {
return partition(reverse(str), n).map(reverse).reverse();
};
var repeat = function (str, n) {
return new Array(n + 1).join(str);
};
var ljust = function (str, n, ch) {
var length = str.length;
ch = ch || ' ';
if (length >= n) {
return str;
}
return (repeat(ch, n) + str).slice(-n);
};
var zfill = function (str, n) {
return ljust(str, n, '0');
};
ascii.noConflict = function () {
root.ascii = prevAscii;
return ascii;
};
ascii.encode = function encode(str) {
var
index = 0,
length = str.length,
concat,
result = '';
for (; index < length; ++index) {
concat = rpartition(str.charCodeAt(index).toString(16), 2);
concat.forEach(function (str) {
result += zfill(str, 2).slice(-2);
});
}
return result;
};
ascii.decode = function (str) {
if (typeof str === 'number') {
str = str.toString(16);
}
return partition(str, 2).map(function (element) {
return String.fromCharCode(parseInt(element, 16));
}).join('');
};
}).call(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment