Permalink
Browse files

Merge pull request #2 from maximumhallinan/support_negative_indices

Add support for negative indices
  • Loading branch information...
sindresorhus committed Jul 14, 2015
2 parents a5f685d + f4fdcd1 commit a5c2a4fe65c1cad96600c8826daf4a6339dc2c1b
Showing with 28 additions and 2 deletions.
  1. +6 −1 index.js
  2. +1 −0 package.json
  3. +4 −1 readme.md
  4. +17 −0 test.js
@@ -1,14 +1,19 @@
'use strict';
var arrify = require('arrify');
var numSort = require('num-sort');
var arrayUniq = require('array-uniq');
module.exports = function (str, i, opts) {
opts = opts || {};
var ret = [];
var lastIndex = 0;
arrify(i).sort(numSort.asc).forEach(function (el) {
arrayUniq(arrify(i).map(function (el) {
var val = el < 0 ? ((str.length - 1) - (el * -1)) : el;
return val < 0 ? (val * -1) : val;
}).sort(numSort.asc)).forEach(function (el) {
el++;
ret.push(str.slice(lastIndex, opts.remove ? el - 1 : el));
lastIndex = el;
@@ -30,6 +30,7 @@
"indices"
],
"dependencies": {
"array-uniq": "^1.0.2",
"arrify": "^1.0.0",
"num-sort": "^1.0.0"
},
@@ -18,6 +18,9 @@ var splitAt = require('split-at');
splitAt('unicorn', 2);
//=> ['uni', 'corn']
splitAt('unicorn', -2);
//=> ['unico', 'rn']
splitAt('unicorn&rainbow', [6, 7]);
//=> ['unicorn', '&', 'rainbow']
@@ -40,7 +43,7 @@ String to be split.
Type: `number`, `array` of `number`
One or more indices.
One or more indices. A negative index is a 1-based position from the end of the string. For example, -1 is the index of the last place in the string. Duplicate indices are removed from the `index` array. A negative index and positive index that refer to the same position in the string are treated as duplicates.
#### options
17 test.js
@@ -5,16 +5,28 @@ var splitAt = require('./');
test('splitAt()', function (t) {
assert.deepEqual(splitAt('unicorn', 2), ['uni', 'corn']);
assert.deepEqual(splitAt('unicorn', -2), ['unico', 'rn']);
assert.deepEqual(
splitAt('unicorn & rainbows', [6, 13, 2, 9]),
['uni', 'corn', ' & ', 'rain', 'bows']
);
assert.deepEqual(
splitAt('unicorn & rainbows', [-6, -13, -2, -9]),
['unico', 'rn &', ' ra', 'inbo', 'ws']
);
assert.deepEqual(splitAt('unicorn', 5), ['unicor', 'n']);
assert.deepEqual(splitAt('unicorn', 6), ['unicorn']);
assert.deepEqual(splitAt('unicorn', -1), ['unicor', 'n']);
assert.deepEqual(splitAt('unicorn', 100), ['unicorn']);
assert.deepEqual(splitAt('unicorn', -100), ['unicorn']);
assert.deepEqual(splitAt('unicorn', [-4, 2]), [ 'uni', 'corn' ]);
t.end();
});
@@ -24,6 +36,11 @@ test('remove option', function (t) {
['unicorn', 'rainbow']
);
assert.deepEqual(
splitAt('unicorn&rainbow', -7, {remove: true}),
['unicorn', 'rainbow']
);
assert.deepEqual(
splitAt('foo|bar|baz', [3, 7], {remove: true}),
['foo', 'bar', 'baz']

0 comments on commit a5c2a4f

Please sign in to comment.