Skip to content

Instantly share code, notes, and snippets.

@hperrin
Last active January 12, 2022 07:35
Show Gist options
  • Save hperrin/8ffe2146e81da81facfd3be42dfbde0c to your computer and use it in GitHub Desktop.
Save hperrin/8ffe2146e81da81facfd3be42dfbde0c to your computer and use it in GitHub Desktop.

Revisions

  1. hperrin revised this gist Jan 12, 2022. 2 changed files with 14 additions and 11 deletions.
    11 changes: 7 additions & 4 deletions splitn.js
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,7 @@
    export default const splitn = (s, d, n = Infinity) => s.split(d).reduce(
    (a, c) => (a.length === n ? a[a.length-1] = [a[a.length-1], c].join(d) : a.push(c)) && a,
    []
    );
    export default const splitn = (s, d, n = Infinity) => {
    const a = s.split(d);
    return [
    ...a.slice(0, n - 1),
    ...(a.length >= n ? [a.slice(n - 1).join(d)] : [])
    ];
    };
    14 changes: 7 additions & 7 deletions splitn.ts
    Original file line number Diff line number Diff line change
    @@ -1,7 +1,7 @@
    export default const splitn = (s: string, d: string, n = Infinity) => s.split(d).reduce(
    (a: string[], c: string) =>
    ((a.length === n
    ? (a[a.length - 1] = [a[a.length - 1], c].join(d))
    : a.push(c)) && a) as unknown as string[],
    []
    );
    export default const splitn = (s: string, d: string, n = Infinity) => {
    const a = s.split(d);
    return [
    ...a.slice(0, n - 1),
    ...(a.length >= n ? [a.slice(n - 1).join(d)] : [])
    ];
    };
  2. hperrin revised this gist Jan 12, 2022. 1 changed file with 7 additions and 0 deletions.
    7 changes: 7 additions & 0 deletions splitn.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,7 @@
    export default const splitn = (s: string, d: string, n = Infinity) => s.split(d).reduce(
    (a: string[], c: string) =>
    ((a.length === n
    ? (a[a.length - 1] = [a[a.length - 1], c].join(d))
    : a.push(c)) && a) as unknown as string[],
    []
    );
  3. hperrin created this gist Jan 12, 2022.
    4 changes: 4 additions & 0 deletions splitn.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,4 @@
    export default const splitn = (s, d, n = Infinity) => s.split(d).reduce(
    (a, c) => (a.length === n ? a[a.length-1] = [a[a.length-1], c].join(d) : a.push(c)) && a,
    []
    );