BING
Surmon's digital vihara
OG

JavaScript 代码片段合集

1,365 characters, 3 min read2017/07/03 PM4,720 views

1. 返回一个已排序的可循环对象

          
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
var dist = {'a': ['A', 3], 'c': ['B', 4], 'b': ['C', 2], 'e': ['A', 2.7], 'd': ['B', 1]} Object.keys(dist).reduce((r, i) => { if (r[dist[i][1]] == undefined || r[dist[i][1]] > i) r[dist[i][1]] = i return r }, {})

2. 最简单的方式实现依赖注入

          
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
/** * Constructor DependencyInjector * @param {Object} - object with dependencies */ class DI { constructor(dependency) { this.dependency = dependency } inject(func) { let deps = /^[^(]+\(([^)]+)/.exec(func.toString()) // 构建参数绑定数组 deps = !deps ? [] : deps[1].split(/\s?,\s?/).map(dep => this.dependency[dep]) return function () { return func.apply(this, deps) } } }

3. 实现一个字符串形式的 IP 地址,转为 INT 整型保存,及逆转方法

          
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
const ip2int = function(ip) { var num = 0 ip = ip.split(".") num = Number(ip[0]) * 256 * 256 * 256 + Number(ip[1]) * 256 * 256 + Number(ip[2]) * 256 + Number(ip[3]) num = num >>> 0 return num } /** * 数字转ip * @param num * @returns {string|*} * @private */ /*global _int2ip(num: number) */ const int2iP = function(num) { var str var tt = new Array() tt[0] = (num >>> 24) >>> 0 tt[1] = ((num << 8) >>> 24) >>> 0 tt[2] = (num << 16) >>> 24 tt[3] = (num << 24) >>> 24 str = String(tt[0]) + "." + String(tt[1]) + "." + String(tt[2]) + "." + String(tt[3]) return str }
Creative Commons BY-NC 4.0 https://surmon.me/article/62
1 / 1 comments
Guest
Join the discussion...
  • 原研药
    原研药🇨🇳CNShenzheniOSWeChat

    这样e e