OILS / stdlib / ysh / list.ysh View on Github | oils.pub

53 lines, 39 significant
1const __provide__ = :| any all repeat |
2
3func any(list) {
4 ### Returns true if any value in the list is truthy.
5 # Empty list: returns false
6
7 for item in (list) {
8 if (item) {
9 return (true)
10 }
11 }
12 return (false)
13}
14
15func all(list) {
16 ### Returns true if all values in the list are truthy.
17 # Empty list: returns true
18
19 for item in (list) {
20 if (not item) {
21 return (false)
22 }
23 }
24 return (true)
25}
26
27func repeat(x, n) {
28 ### Repeats a given Str or List, returning another Str or List
29
30 # Like Python's 'foo'*3 or ['foo', 'bar']*3
31 # negative numbers are like 0 in Python
32
33 var t = type(x)
34 case (t) {
35 Str {
36 var parts = []
37 for i in (0 ..< n) {
38 call parts->append(x)
39 }
40 return (join(parts))
41 }
42 List {
43 var result = []
44 for i in (0 ..< n) {
45 call result->extend(x)
46 }
47 return (result)
48 }
49 (else) {
50 error "Expected Str or List, got $t"
51 }
52 }
53}