helper.js
2.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
/*
## Helpers
*/
var Util = require('../util')
module.exports = {
// 把字符串的第一个字母转换为大写。
capitalize: function(word) {
return (word + '').charAt(0).toUpperCase() + (word + '').substr(1)
},
// 把字符串转换为大写。
upper: function(str) {
return (str + '').toUpperCase()
},
// 把字符串转换为小写。
lower: function(str) {
return (str + '').toLowerCase()
},
// 从数组中随机选取一个元素,并返回。
pick: function pick(arr, min, max) {
// pick( item1, item2 ... )
if (!Util.isArray(arr)) {
arr = [].slice.call(arguments)
min = 1
max = 1
} else {
// pick( [ item1, item2 ... ] )
if (min === undefined) min = 1
// pick( [ item1, item2 ... ], count )
if (max === undefined) max = min
}
if (min === 1 && max === 1) return arr[this.natural(0, arr.length - 1)]
// pick( [ item1, item2 ... ], min, max )
return this.shuffle(arr, min, max)
// 通过参数个数判断方法签名,扩展性太差!#90
// switch (arguments.length) {
// case 1:
// // pick( [ item1, item2 ... ] )
// return arr[this.natural(0, arr.length - 1)]
// case 2:
// // pick( [ item1, item2 ... ], count )
// max = min
// /* falls through */
// case 3:
// // pick( [ item1, item2 ... ], min, max )
// return this.shuffle(arr, min, max)
// }
},
/*
打乱数组中元素的顺序,并返回。
Given an array, scramble the order and return it.
其他的实现思路:
// https://code.google.com/p/jslibs/wiki/JavascriptTips
result = result.sort(function() {
return Math.random() - 0.5
})
*/
shuffle: function shuffle(arr, min, max) {
arr = arr || []
var old = arr.slice(0),
result = [],
index = 0,
length = old.length;
for (var i = 0; i < length; i++) {
index = this.natural(0, old.length - 1)
result.push(old[index])
old.splice(index, 1)
}
switch (arguments.length) {
case 0:
case 1:
return result
case 2:
max = min
/* falls through */
case 3:
min = parseInt(min, 10)
max = parseInt(max, 10)
return result.slice(0, this.natural(min, max))
}
},
/*
* Random.order(item, item)
* Random.order([item, item ...])
顺序获取数组中的元素
[JSON导入数组支持数组数据录入](https://github.com/thx/RAP/issues/22)
不支持单独调用!
*/
order: function order(array) {
order.cache = order.cache || {}
if (arguments.length > 1) array = [].slice.call(arguments, 0)
// options.context.path/templatePath
var options = order.options
var templatePath = options.context.templatePath.join('.')
var cache = (
order.cache[templatePath] = order.cache[templatePath] || {
index: 0,
array: array
}
)
return cache.array[cache.index++ % cache.array.length]
}
}