An array is a simple "data structure." But it is versatile. Its "indexed" nature (you can access any element simply by an integer that acts like its index) is powerful. Here's a zero-indexed n-element array named xs. The indices run from 0 to n-1.
Its power is revealed when we analyze its structure closely: xs[i] is the element at the index i.
Use an array to write this function, let's call it histogram:
1) It is applied to an argument that is a string; a string is a sequence of UTF-16 code units (characters) in JavaScript.
2) The string contains only lower-case ASCII characters (from 'a' to 'z'). Fortunately, they are arranged sequentially in UTF-16. You can easily verify that by using the charCodeAt(index) method. For example, that method returns the integer 97 for a.
3) The function should return an array that tells us how many of each of the characters ('a' to 'z') are in that string. Thus, the array is the histogram of the given string as far as the characters ('a' to 'z') are concerned.
An array is a simple "data structure." But it is versatile. Its "indexed" nature (you can access any element simply by an integer that acts like its index) is powerful. Here's a zero-indexed
n
-element array namedxs
. The indices run from0
ton-1
.Its power is revealed when we analyze its structure closely:
xs[i]
is the element at the indexi
.Use an array to write this function, let's call it
histogram
:1) It is applied to an argument that is a string; a string is a sequence of UTF-16 code units (characters) in JavaScript. 2) The string contains only lower-case ASCII characters (from
'a'
to'z'
). Fortunately, they are arranged sequentially in UTF-16. You can easily verify that by using thecharCodeAt(index)
method. For example, that method returns the integer97
fora
. 3) The function should return an array that tells us how many of each of the characters ('a'
to'z'
) are in that string. Thus, the array is the histogram of the given string as far as the characters ('a'
to'z'
) are concerned.Try to get the abstraction right!