-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathfrom.js
111 lines (90 loc) · 2.33 KB
/
from.js
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
/**
* The Array.from() static method creates a new, shallow-copied Array instance from an array-like or iterable object.
*/
const log = console.log
// Array from a String
log(Array.from('foo'))
// [ "f", "o", "o" ]
// Array from a Set
const set = new Set(['foo', 'bar', 'baz', 'foo'])
log(Array.from(set))
// [ "foo", "bar", "baz" ]
// Array from a Map
const map = new Map([
[1, 2],
[2, 4],
[4, 8],
])
log(Array.from(map))
// [[1, 2], [2, 4], [4, 8]]
const mapper = new Map([
['1', 'a'],
['2', 'b'],
])
log(Array.from(mapper.values()))
// ['a', 'b'];
log(Array.from(mapper.keys()))
// ['1', '2'];
// Array from an Array-like object (arguments)
function f() {
return Array.from(arguments)
}
log(f(1, 2, 3))
// [ 1, 2, 3 ]
// Using arrow functions and Array.from()
// Using an arrow function as the map function to
// manipulate the elements
log(Array.from([1, 2, 3], (x) => x + x))
// [2, 4, 6]
// Generate a sequence of numbers
// Since the array is initialized with `undefined` on each position,
// the value of `v` below will be `undefined`
log(Array.from({ length: 5 }, (v, i) => i))
// [0, 1, 2, 3, 4]
// Sequence generator (range)
// Sequence generator function (commonly referred to as "range", e.g. Clojure, PHP etc)
const range = (start, stop, step) =>
Array.from({ length: (stop - start) / step + 1 }, (_, i) => start + i * step)
// Generate numbers range 0..4
log(range(0, 4, 1))
// [0, 1, 2, 3, 4]
// Generate numbers range 1..10 with step of 2
log(range(1, 10, 2))
// [1, 3, 5, 7, 9]
// Generate the alphabet using Array.from making use of it being ordered as a sequence
log(
range('A'.charCodeAt(0), 'Z'.charCodeAt(0), 1).map((x) =>
String.fromCharCode(x)
)
)
// ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
//fill array with 0
log(Array.from({ length: 3 }, () => 0))
const json = {
name: "rama"
}
log(Array.from(JSON.stringify(json)))
function squared(max){
return {
[Symbol.iterator](){
let n =0;
return {
next(){
n++
if(n<=max){
return {
value:n*n,
done:false
}
}else{
return {
value:undefined,
done:true
}
}
}
}
}
}
}
log(Array.from(squared(10)))