2013年4月20日土曜日

PHPをインスパイアしたJavaScriptスニペット

sitepointで投稿されたPHPの関数をインスパイアしたJavaScriptのスニペット。実際に使うケースは少ないとは思いますが、面白いアプローチだったので紹介します。コメント欄にてphp.js というライブラリも紹介されていました。

1. unique()

PHPのarray_unique()。配列の中で重複した値を返します。

Array.prototype.unique = function (sort, sortingFunction) {
  var array = [];
  for (var i = 0; i < this.length; i++) {
    if (array.inArray(this[i]) === false)
      array.push(this[i]);
  }
  if (sort === true) {
    if (typeof sortingFunction === 'function')
      array.sort(sortingFunction);
    else
      array.sort();
  }
  return array;
};

var array = [1, 2, 9, 6, 2, 1, 9, 3];
console.log(array.unique()); // print [1, 2, 9, 6, 3]
console.log(array.unique(true)); // print [1, 2, 3, 6, 9]

2. htmlSpecialChars()

PHPのhtmlspecialchars()。特殊文字を HTMLエンティティに変換。

String.prototype.htmlSpecialChars = function(){
  return this
         .replace(/&/g, '&amp;')
         .replace(/</g, '&lt;')
         .replace(/>/g, '&gt;')
         .replace(/"/g, '&quot;');
};

var string = 'Me, myself & I like to "code" <html>';
console.log(string);
// print Me, myself & I like to "code" <html>
string = string.htmlSpecialChars();
console.log(string);
// print Me, myself &amp; I like to &quot;code&quot; &lt;html&gt;

3. htmlSpecialCharsDecode()

PHPのhtmlspecialchars_decode()。特殊な HTML エンティティを文字に戻します。

String.prototype.htmlSpecialCharsDecode = function(){
  return this
         .replace(/&amp;/g, '&')
         .replace(/&lt;/g, '<')
         .replace(/&gt;/g, '>')
         .replace(/&quot;/g, '"');
};

var string = 'Me, myself & I like to "code" <html>';
console.log(string);
// print Me, myself & I like to "code" <html>
string = string.htmlSpecialChars();
console.log(string);
// print Me, myself &amp; I like to &quot;code&quot; &lt;html&gt;
string = string.htmlSpecialCharsDecode();
console.log(string);
// print Me, myself & I like to "code" <html>

4. ucwords()

PHPのucwords()。文字列の各単語の最初の文字を大文字にします。

String.prototype.ucwords = function() {
  var words = this.split(/(\s+)/);
  for(var i = 0; i < words.length; i++)
    words[i] = words[i][0].toUpperCase() + words[i].substr(1, words[i].length);
  return words.join('');
};

var string = 'my name is aurelio de rosa';
console.log(string.ucwords());
// print My Name Is Aurelio De Rosa

5. ucfirst()

PHPのucfirst()。文字列の最初の文字を大文字にします。

String.prototype.ucfirst = function() {
  var words = this.split(/(\s+)/);
  if (words[0] != null)
     words[0] = words[0][0].toUpperCase() + words[0].substr(1, words[0].length);
  return words.join('');
};

var string = 'my name is aurelio de rosa';
console.log(string.ucfirst());
// print My name is aurelio de rosa

後記


JavaScriptでもjQueryやUnderscore.jsなどのライブラリを使うことが前提のケースがほとんどなので上記のような実装をすることは無いとは思いますが、他言語の便利な関数を移植するために考えることは、よい勉強になりました。


0 件のコメント:

コメントを投稿