

These classes have identical interfaces into JavaScript's built-in Array and String objects. We've looked already at how range() can be used to constuct slice-able arrays the one other thing you need to know is how to construct SliceArray and SliceString instances manually. Once you get used to how the Python syntax maps to the double bracket syntax, it becomes quite easy to switch seamlessly between the two. Here are a few examples of how the syntax compares between Python and Slice in JavaScript. In fact, part of the test suite actually runs a Python script to perform thousands of slicing operations to verify that the JavaScript results are identical! It supports negative indexing, empty parameters, extended slices, negative steps, assignment to slices, and the whole shebang. The slicing will work exactly as you would expect in Python after that. It's not possible to replicate that exact syntax in JavaScript, but Slice uses a very similar syntax that should be immediately familiar to you if you know Python.Īll you need to do is to use double brackets for the indexing and to replace the colons with commas. The range() method returns a SliceArray so that the return value immediately supports slicing for convenience.įor example, you could run the following without needing to explicitly construct a SliceArray. This choice was made because Python has built-in support for its slice syntax, but JavaScript requires subclassing String and Array in order to add support for a similar syntax. One major difference is that range() produces an iterator in Python while it produces a fully populated SliceArray in JavaScript, similar to how range() worked in Python 2. The method signatures of these methods are identical to those used in Python, and the behavior and usage of them is very similar. Python includes two built-in functions that Slice provides analogues of: range() and slice().

The methods and syntax that it introduces are designed to very closely mirror those from Python. If you know Python already, then you'll be right at home with Slice. It provides some context for why this library exists and works the way that it does. You also might find the For People Who Know Python Already section interesting, even if you've never used Python before. If you're ready to give it a try, then head over to the installation section or take a look at the API documentation.
