Skip to content

Instantly share code, notes, and snippets.

@pehaa

pehaa/patternCount.js

Last active Feb 26, 2020
Embed
What would you like to do?
CodePen Home Tartans Palette + Threadcount into an array of Stripes
const countPattern = (threadcount, palette, multiplier = 4) => {
// transforms pallette K#303030 W#FFFFFF string into an objet {K: '#303030', W: '#FFFFFF'}
palette = palette.split(" ").reduce((acc, curr) => {
const el = curr.split("#")
acc[el[0].trim()] = `#${[el[1]]}`
return acc
}, {})
threadcount = threadcount.split(" ")
let result = []
let total = 0
const colCountArray = threadcount.map((el, index) => {
// regex to separate color code and number of threads
const regex = /([a-zA-Z]+|\(.*?\))(\/?)(\d+)/gm
const m = regex.exec(el)
if (m !== null) {
total +=
index === 0 || index === threadcount.length - 1 ? 1 * m[3] : 2 * m[3]
return { fill: palette[m[1]], size: multiplier * m[3] }
}
return { fill: "#000000", size: 0 }
})
// "/" means that the pattern need to be reflected
if (threadcount[0].indexOf("/") > -1) {
for (let i = 0; i < 2 * threadcount.length - 2; i++) {
const index =
i < threadcount.length - 1 ? i : 2 * threadcount.length - 2 - i
result.push(colCountArray[index])
}
/* threads are multiplied by 4 but the whole tile needs to be disisible by 8
so that the grating mask is seamless, that's equivalent by total being even */
if (total % 2) {
for (let i = 0; i < 2 * threadcount.length - 2; i++) {
result.push(result[i])
}
}
} else {
for (let i = 0; i < threadcount.length; i++) {
result.push(colCountArray[i])
}
/* threads are multiplied by 4 but the whole tile needs to be disisible by 8
so that the grating mask is seamless, that's equivalent by total being even */
if (total % 2) {
for (let i = 0; i < threadcount.length - 1; i++) {
result.push(result[i])
}
}
}
return result
}
const palette = "O#FF8A00 P#E52E71 W#FFFFFF K#100E17"
const threadcount = "O/40 P10 W10 P70 K/10"
console.log(countPattern(threadcount, palette, 1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment