[Javascript] 數據處理: Lodash.js

Lodash
https://lodash.com/

Lodash英文版線上手冊
https://lodash.com/docs/

Lodash簡體版線上手冊
http://lodash.think2011.net/

Lodash FP Guide函數式程式語言指引
https://github.com/lodash/lodash/wiki/FP-Guide

Lodash 4.0版相較3.0新增多種方法,並放棄對IE6至IE8的支持,詳細更新內容見:
https://segmentfault.com/a/1190000004305586

網頁前端Javascript套件Lodash.js一開始是Underscore庫的一個fork,開發者John-David Dalton的最初目標是提供更多一致的跨流覽器行為,並改善Underscore性能,但因為和其他(Underscore的)貢獻者意見相左,故從中獨立出來。

Lodash可以把它看成是對JavaScript底層的功能擴充,知名JavaScript庫 jQuery也是有自行擴充對陣列的操作。像是Function、Array、Object這些原生的物件,Lodash都亦增加了許多方法,相較於JQuery非常多,可說是專門處理數據或進行演算法開發的JavaScript擴充函式庫。且如同jQuery在全部函數前加全域的「$」一樣,Lodash可使用全域的底線「_」符號來進行快速呼叫使用。

Lodash於3.0對鏈式方法(chain method)進行延遲計算,意味著在調用.value()之前不會執行各函式的實體,因此Lodash可以進行如short cut fusion(以最佳化方法整併多種函式成一被呼叫的函式)優化,藉此降低運算次數來達到效能的提昇。而Lodash另一種特性是便利於將Javascript以函數式程式語言(Functional Programming)的思路推進,實踐函式之交換律與結合律等諸多數學性質。

以下為FP版

lodash FP Guide
https://github.com/lodash/lodash/wiki/FP-Guide

Functional Programming With Lodash/FP
https://blog.codeminer42.com/functional-programming-with-lodash-fp-8fe0619b3024


以下為單html檔測試範例︰
<!DOCTYPE html>
<html>
<head>
    <title>Lodash Demo</title>
    <meta charset="utf-8">

    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

    <script>


      let t1 = _.union([2, 1], [4, 2], [1, 2]);
      console.log(t1)
      //Array [ 2, 1, 4 ]


      let t2 = _.zipObject(['a', 'b'], [1, 2]);
      console.log(t2)
      //Object { a: 1, b: 2 }
    
    
      let t3 = _.without([1, 2, 1, 3, 5, 6, 7], 1, 2);
      console.log(t3)
      //Array [ 3, 5, 6, 7 ]
    
    
      function square(n) {
        return n * n;
      }
      let t4 = _.map({ 'a': 4, 'b': 8 }, square);
      console.log(t4)
      //Array [ 16, 64 ]
    
    
      let t5 = _.shuffle([1, 2, 3, 4]);
      console.log(t5)
      //Array [ 3, 1, 4, 2 ], 因隨機排序故可能非顯示此組數據
    
    
      let t6 = _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort');
      console.log(JSON.stringify(t6))
      //[[1,5,7],[1,2,3]]
    
    
      let users = [
        { 'user': 'fred',   'age': 48 },
        { 'user': 'barney', 'age': 36 },
        { 'user': 'fred',   'age': 42 },
        { 'user': 'barney', 'age': 34 }
      ];
      let t7 = _.sortBy(users, function(o) { return o.age; });
      console.log(JSON.stringify(t7))
      //[{"user":"barney","age":34},{"user":"barney","age":36},{"user":"fred","age":42},{"user":"fred","age":48}]
    
    
      let t8 = _.chain({ 'a': 3, 'b': 7, 'c': 3 })
      .map(function (v) {
          return 'uniq:' + v;
      })
      .uniq()
      .join(', ')
      .value();
      console.log(t8)
      //uniq:3, uniq:7
    

    </script>

</head>
<body>
</body>
</html>


#Javascript, lodash, fp, web, 函數式語言, 網頁

留言