Browse Source

[array.split]: add split function

mightyplow 7 years ago
parent
commit
3ebb0f6149
4 changed files with 21 additions and 2 deletions
  1. 11 0
      src/array/__tests__/split.test.js
  2. 2 1
      src/array/index.js
  3. 6 0
      src/array/split.js
  4. 2 1
      src/index.js

+ 11 - 0
src/array/__tests__/split.test.js

@@ -0,0 +1,11 @@
+import split from '../split';
+
+export default test => {
+    test.ok(typeof split === 'function', 'split should be a function');
+    test.ok(Array.isArray(split()), 'should return an array');
+
+    test.ok(split([1, 2, 3, 4], 2).length === 2, 'should split into chunks');
+    test.ok(split([1, 2, 3, 4], 2).every((ar) => ar.length === 2), 'should split into chunks of size 2');
+
+    test.done();
+};

+ 2 - 1
src/array/index.js

@@ -6,6 +6,7 @@ export { default as ensureArray} from './ensureArray';
 export { default as flatten } from './flatten';
 export { default as getDefinedValues } from './getDefinedValues'
 export { default as head } from './head';
+export { default as split } from './split';
 export { default as tail } from './tail';
 export { default as toArray } from './toArray';
-export { default as unique } from './unique';
+export { default as unique } from './unique';

+ 6 - 0
src/array/split.js

@@ -0,0 +1,6 @@
+export default function split (ar, chunkSize) {
+    return (function innerSplit (rest = [], result = []) {
+        if (!rest.length) { return result; }
+        return innerSplit(rest.slice(chunkSize), result.concat([rest.slice(0, chunkSize)]));
+    }(ar));
+}

+ 2 - 1
src/index.js

@@ -4,6 +4,7 @@ export {
     flatten,
     getDefinedValues,
     head,
+    split,
     tail,
     toArray,
     unique
@@ -46,4 +47,4 @@ export {
     isRuleType,
     getRules,
     createStylesheetAst
-} from './stylesheet';
+} from './stylesheet';