0

How to make a slice function manually and be invoked similar or very close to the way it is done in JavaScript, for example:

let arr = [0, 1, 2, 3, 4, 5]

JS Function:

  arr = arr.slice(1, 3)  //it returns: [1,2]

The result I want:

 arr = arr.myManualSlice(1, 3) //it returns: [1,2]

If this example above is impossible to do, I would like to do it as closely as possible. The closest I was able to do was like this below:

function myManualSlice(arr, init, end) {
    let result = []

    if (end == null) {

        for (let i = 0; i < arr.length; i++) {
            if (i >= init) {
                result.push(arr[i])
            }
        }
    } else {

        for (let i = 0; i < arr.length; i++) {
            if (i >= init && i < end) {
                result.push(arr[i])
            }
        }
    }

    return result
}


let arr = [0, 1, 2, 3, 4, 5]

My closest result:

arr = myManualSlice(arr, 1, 3) //it returns: [1,2]

NOTE: I'm not interested in how best to make the body of the function as there are tons of different ways to do it and the function is returning what I expect. I'm only interested in doing the function invocation close to the JavaScript slice way. The logic of the function body can only be changed for this purpose.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
claudiopb
  • 1,056
  • 1
  • 13
  • 25
  • 1
    It is very hard to guess what the aim of this is. Is it for educational purposes, why do you not care how the implementation is? It sounds like you want to [extend the Array prototype](https://stackoverflow.com/questions/8859828/javascript-what-dangers-are-in-extending-array-prototype) - that is the way to get `arr.myManualSlice(1, 3)` to work – mplungjan Dec 31 '21 at 10:10
  • Thank you! Yes, that's exactly what you predicted. The aim was only for educational purposes and to understand the language in an 'under the hood' way. I didn't have any problems to solve that forced me to develop this solution. This topic has already been closed. – claudiopb Apr 14 '22 at 13:56

0 Answers0