Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add String slicing #4

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,6 @@ Found something interesting? Please add it here :-)
- All server-side platforms including NodeJS.

## Roadmap
- Add `String` slicing
- Write unit tests

## Release History
Expand Down
27 changes: 18 additions & 9 deletions _s.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,15 @@
var VERSION = '0.2.0';

var _s = function (arr, expr) {
var isStr = /string/.test(Object.prototype.toString.call(arr).toLowerCase());

var length = arr.length;

if (isStr) {
var str = Array.prototype.slice.call(arr);
length = str.length;
}

var exprParts = expr.split(':');

if (exprParts.length > 0) {
Expand All @@ -31,7 +40,7 @@
var arr = arr.slice(0);

//return empty array if given array is empty
if (arr.length == 0) {
if (length == 0) {
return [];
}

Expand All @@ -43,12 +52,12 @@
//set default for `from` if they are not defined
if (isNaN(from)) {
// default value depends on reverse or not
from = step < 0 ? arr.length : 0;
from = step < 0 ? length : 0;
}

//change `from` if we have negative `from`
if (from < 0) {
from = arr.length + from + 1;
from = length + from + 1;
}

//set default for `to` if they are not defined
Expand All @@ -58,27 +67,27 @@
to = from + 1;
} else {
// default value depends on reverse or not
to = step < 0 ? 0 : arr.length;
to = step < 0 ? 0 : length;
}
}

//change `to` if we have negative `to`
if (to < 0) {
to = arr.length + to + 1;
to = length + to + 1;
}

//reverse the array if we have negative `step`
if (step < 0) {
arr = arr.reverse();
isStr ? str = str.reverse() : arr = arr.reverse();

to = arr.length - to;
from = arr.length - from;
to = length - to;
from = length - from;

step = Math.abs(step);
}

//slice the array with `from` and `to` variables
var slicedArr = arr.slice(from, to);
var slicedArr = isStr ? str.slice(from, to) : arr.slice(from, to);

//return sliced array if there is no `step` value
if (isNaN(step)) {
Expand Down