Skip to content

Instantly share code, notes, and snippets.

@esperia
Last active September 30, 2015 12:37
Show Gist options
  • Save esperia/1790281 to your computer and use it in GitHub Desktop.
Save esperia/1790281 to your computer and use it in GitHub Desktop.
CPANのshorten_urlをJavaScript/PHPで移植。
/**
* Make shorten url.
*
* work fine on node.js.
*
* via http://search.cpan.org/~alexbio/Algorithm-URL-Shorten-0.06/lib/Algorithm/URL/Shorten.pm
* based version 0.06.
*/
/*
How to use:
var shorten = require('shorten_url');
var shorts = shorten.shorten_url('http://perl.org');
console.log(shorts);
result :
iqGzim
S515va
qmKrq8
HXv4HD
*/
var crypto = require('crypto');
/**
* make md5 string
* ex.) 912ec803b2ce49e4a541068d495ab570
*/
function md5_hex(data) {
if (!data) return null;
if (typeof data !== 'string') {
data = data.toString();
}
var hex = crypto.createHash('md5').
update(data).
digest('hex');
return hex;
}
exports.shorten_url = function (url) {
var chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
var hex = md5_hex(url);
var output = [];
for (var i=0; i < hex.length / 8; i++) {
var sub_hex = hex.substr(i * 8, 8);
var toInt = parseInt(sub_hex, 16);
var out = '';
for (var j=0; j < 6; j++) {
var val = 0x3D & toInt;
out += chars[val];
toInt = toInt >> 5;
}
output.push(out);
}
return output;
}
/**
* Copyright 2011 Alessandro Ghedini.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of either: the GNU General Public License as published
* by the Free Software Foundation; or the Artistic License.
*
* See http://dev.perl.org/licenses/ for more information.
*
*
* forked by @esperia09
*/
<?php
function shorten_url($data) {
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$hex = hash('md5', $data);
$output = array();
for ($i = 0; $i<strlen($hex) / 8; $i++) {
$sub_hex = substr($hex, $i * 8, 8);
$int = hexdec($sub_hex);
$out = '';
for ($j = 0; $j < 6; $j++) {
$val = 0x3D & $int;
$out .= $chars{$val};
$int = $int >> 5;
}
$output[] = $out;
}
return $output;
}
//var_dump(shorten_url('http://perl.org'));
/*
array(4) {
[0]=>
string(6) "iqGzim"
[1]=>
string(6) "S515va"
[2]=>
string(6) "qmKrq8"
[3]=>
string(6) "HXv4HD"
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment