This article aims to provide a clear understanding of the slice function in Make and the differences between zero-based and one-based indexing. Both of these concepts are used in Make, but they are not documented completely.
What is the purpose of the slice function in Make?
The slice function in Make is used to select a specific subset of items from an array. The syntax for the function is:
slice(array, start, [end]).
- The first argument, ‘array’, is the array from which items are to be selected.
- The second argument, ‘start’, is the index of the first item to be included in the new array.
- The third argument, ‘end’, is optional and is the index of the last item to be included in the new array.
If the end argument is not specified, the function will slice the array till the end by default. The slice function is an important tool for manipulating arrays and can be used to extract subsets of data or divide an array into smaller arrays.
So, what about the zero-based- and one-based indexes?
It’s important to note that the slice function uses a zero-based index. This means that the first item in the array is indexed at 0, the second item is indexed at 1, and so on. This may be confusing for non-technical users who are used to the one-based indexing used in the
Ok, and now some example…
To illustrate the usage of the slice function, consider the following example: If we have an array like
["1","2","3","4","5"], and we want to create a new array with only the first 3 elements, we would use the function
slice(array,0,3). This will return a new array containing
["1", "2", "3"]. To get the last two elements of the array, we would use the function
slice(array,3). This will return a new array containing
It’s important to note that the ending index of the slice function is not inclusive, meaning that the element at the ending index will not be included in the new array. Additionally, the slice function returns a new array containing only selected items, so the original array remains unchanged.
In addition, the slice function also allows for negative indexing. If you pass -1 as the end index, it will select all items from the start index till the end of the array. Similarly, -2 will select all elements from the start index till the second last element, and so on.
Worth mentioning as well, is that the substring text function in Make works with the same index logic as the slice function. This means that it also uses a zero-based index system, where the first character in the string is indexed at 0, the second character is indexed at 1, and so on.
For example, the function
substring("Hello World!", 0, 5) will result in
Hello, which is the substring of the original text that starts at the 0th index and goes till the 5th index. This function can be used to extract specific parts of a string, similar to how the slice function can be used to extract specific parts of an array.
Glenn - Callinetic