Skip to content

Instantly share code, notes, and snippets.

@cyrilf
Created October 18, 2018 09:57
Show Gist options
  • Select an option

  • Save cyrilf/64f2f271c7968a4090d143608bfd59d7 to your computer and use it in GitHub Desktop.

Select an option

Save cyrilf/64f2f271c7968a4090d143608bfd59d7 to your computer and use it in GitHub Desktop.

Revisions

  1. cyrilf created this gist Oct 18, 2018.
    1 change: 1 addition & 0 deletions flattenArray.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1 @@
    const flattenArray = (arr) => arr.reduce((result, value) => result.concat(value), [])
    41 changes: 41 additions & 0 deletions getLabelWithLinks.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    // const termsLabel = "By checking this box you agree to our terms"
    //
    // const links = [
    // { href: "https://something.com", title: "By checking" },
    // { href: "https://somewhere.com", title: "this box" },
    // ]
    //
    // const { label, unmatched } = getLabelWithLinks(termsLabel, links)
    //
    // `label` will be something like:
    // `<span>["", <a href="https://something.com">By checking</a>, " ", <a href="https://somewhere.com">this box</a>, " you agree to our terms", ""]</span>`

    const getLabelWithLinks = (label, links) => {
    const [matched, unmatched] = links.reduce((result, link) => {
    result[label.indexOf(link.title) !== -1) ? 0 : 1].push(link)
    return result
    }, [[], []])

    if (!matched.length) {
    return { label, unmatched }
    }

    let labelResult = matched.reduce((result, link) => {
    result = result.map(part => {
    // if it's not a string OR it is but doesn't contain the link title
    if (typeof part !== "string" || part.indexOf(link.title) === -1) {
    return part
    }

    // split on the title (return an array of [beforeTitle, afterTitle]), and then insert the link in the middle
    part = part.split(link.title)
    return [part[0], <Link key={`${link.title}-${link.href}`} link={link}>{link.title}</Link>, part[1]]
    })

    return flattenArray(result)
    }, [label])

    labelResult = <span>{labelResult}</span>

    return { label: labelResult, unmatched }
    }