Find line breaks (v3)

Revision 3 of this benchmark created on


Setup

const text = `
/*
 * Copyright (c) 2020 The ZMK Contributors
 *
 * SPDX-License-Identifier: MIT
 */

#include <behaviors.dtsi>
#include <dt-bindings/zmk/keys.h>
#include <dt-bindings/zmk/bt.h>
#include <dt-bindings/zmk/matrix-transform.h>

/ {
    keymap {
        compatible = "zmk,keymap";
        label = "keymap";

        default_layer {
            label = "base";
// -------------------
// | 7      |  8  |  9  |
// | 4      |  5  |  6  |
// | 1      |  2  |  3  |
// | MO(1)  |  0  |  .  |
// ----------------------
            bindings = <
    &kp N7 &kp N8 &kp N9
    &kp N4 &kp N5 &kp N6
    &kp N1 &kp N2 &kp N3
    &mo 1  &kp N0 &kp DOT
            >;
        };

        nav_layer {
// -----------------------
// | BTNXT |  HOME  |  PGUP  |
// | BTPRV |  END   |  PGDN  |
// | BTCLR |  _     |  _     |
// | _     |  _     |  RET   |
// -----------------------
            bindings = <
    &bt BT_NXT &kp HOME &kp PG_UP
    &bt BT_PRV &kp END  &kp PG_DN
    &bt BT_CLR &trans   &trans
    &trans     &trans   &kp RET
            >; label = "nav";
        };
    };  label = "test";
};
`;

Test runner

Ready to run.

Testing in
TestOps/sec
indexOf
function getLineBreakPositions(text) {
  const positions = [];
  let index = 0;

  while ((index = text.indexOf("\n", index)) >= 0) {
    positions.push(index);
    index++;
  }

  return positions;
}

getLineBreakPositions(text);
ready
map filter
function getLineBreakPositions(text) {
  return Array.from(text).map((c, i) => c === '\n' ? i : -1).filter(i => i >= 0);
}

getLineBreakPositions(text);
ready
map filter 2
function getLineBreakPositions(text) {
  return [...text].map((c, i) => c === '\n' ? i : -1).filter(i => i >= 0);
}

getLineBreakPositions(text);
ready
foreach
function getLineBreakPositions(text) {
	const positions = [];
	[...text].forEach((c, i) => {
		if (c === '\n') {
			positions.push(i);
		}
	});
	return positions;
}

getLineBreakPositions(text);
ready
for loop
function getLineBreakPositions(text) {
  const positions = [];

  for (let i = 0; i < text.length; i++) {
    if (text[i] === '\n') {
  	  positions.push(i);	
  	}
  }

  return positions;
}

getLineBreakPositions(text);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.