Last active
August 29, 2015 14:07
-
-
Save chrisyip/9a00edb03a0702750b81 to your computer and use it in GitHub Desktop.
faster array-like slicer, aimed to replace [].slice.call(arguments). jsperf http://jsperf.com/from-slice-vs-slice-call
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://github.com/lodash/lodash/blob/51e459b386f8301c803442f7fc722e46fc192d35/lodash.js#L2573 | |
// 2 times faster! | |
function baseSlice(array, start, end) { | |
var index = -1, | |
length = array.length; | |
start = start == null ? 0 : (+start || 0); | |
if (start < 0) { | |
start = -start > length ? 0 : (length + start); | |
} | |
end = (typeof end == 'undefined' || end > length) ? length : (+end || 0); | |
if (end < 0) { | |
end += length; | |
} | |
length = start > end ? 0 : ((end - start) >>> 0); | |
start >>>= 0; | |
var result = Array(length); | |
while (++index < length) { | |
result[index] = array[index + start]; | |
} | |
return result; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Author: Chris Yip <[email protected]> | |
*/ | |
function slice (arrayLike, startPos, endPos) { | |
if (!arrayLike) { | |
return [] | |
} | |
var result = [], | |
i = typeof startPos === 'number' || startPos instanceof Number ? startPos : 0, | |
endIndex = typeof endPos === 'number' || endPos instanceof Number ? endPos : arrayLike.length | |
if (i < 0) { | |
i = i + arrayLike.length | |
if (i < 0) { | |
i = 0 | |
} | |
} | |
if (endIndex < 0) { | |
endIndex = endIndex + arrayLike.length | |
if (endIndex < 0) { | |
endIndex = 0 | |
} | |
} | |
if (endIndex > arrayLike.length) { | |
endIndex = arrayLike.length | |
} | |
for (; i < endIndex; i++) { | |
result[result.length] = arrayLike[i] | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
node 0.11.14 + benchmark 1.0.0