---
title: "Maths editor"
description: "Bill splitter"
canonicalURL: "/tools/billSplitter/"
---
{% extends "_layouts/base.html" %}

{% block head %}
<style>
    .colbox {
        display: flex;
        direction: column;
        align-items: center;
    }

    .padded-floater {
        padding: 5px;
    }
</style>
{% endblock %}

{% block main %}
<h1>Bill splitter</h1>

<label for="splitByInput">Split between <i>n</i>: </label><input style="width: 3rem" value="5" type="number" id="splitByInput">

<div style="padding-top: 1rem;"></div>

<div class="colbox">
    <div><textarea id="inputTextarea" cols="30" rows="10"></textarea></div>
    <div><p class="padded-floater">-></p></div>
    <div><textarea readonly id="outputTextarea" cols="30" rows="10"></textarea></div>
</div>

<div style="padding-top: 1rem;"><button id="exampleButton">example</button></div>

<script defer>
    const splitByNumberInput = document.getElementById("splitByInput");
    const inputTextarea = document.getElementById("inputTextarea");
    const outputTextarea = document.getElementById("outputTextarea");

    const round2dp = (v) => {
        return +(v.toFixed(2))
    }

    const parseLine = (line) => {
        const segments = line.split(" ");
        if (segments.length < 2) {
            return "invalid";
        }
        const x = new Number(segments[0]);
        if (Number.isNaN(x)) {
            return "invalid";
        }
        return {"amount": x, "remainder": segments.slice(1).join(" ")};
    }

    const makeLineScaler = (n) => {
        return (lineObj) => {
            lineObj.amount = round2dp(lineObj.amount / n);
            return lineObj;
        }
    }

    const updateHook = () => {
        const rawInput = inputTextarea.value.trim();
        const inputLines = rawInput.split("\n").filter((v) => {return v != ""});
       
        const scaledLines = inputLines.map(parseLine).map(makeLineScaler(new Number(splitByNumberInput.value)));

        outputTextarea.value = scaledLines.map((v) => {return `${v.amount} ${v.remainder}`}).join("\n") + "\n\ntotal: " + round2dp(scaledLines.reduce((acc, val) => {return val.amount + acc}, 0))
    }

    console.log(splitByNumberInput)

    splitByNumberInput.addEventListener("change", updateHook)
    inputTextarea.addEventListener("keyup", updateHook)

    document.getElementById("exampleButton").addEventListener("click", () => {
        inputTextarea.value = `2 fairy liquid
2.75 bin bags
2.38 kitchen roll x2
1.35 mould spray
5.29 loo rool
10.00 dishwasher tablets`
        updateHook()
    })
</script>
{% endblock %}