Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prettier #55

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"trailingComma": "es5",
"tabWidth": 2,
"semi": false,
"singleQuote": true
}
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,12 @@
"lint-staged": "^8.1.1",
"microbundle": "^0.9.0",
"npm-run-all": "^4.1.5",
"prettier": "^1.16.4",
"static-server": "^2.2.1",
"ts-jest": "^23.10.5",
"tslib": "^1.9.3",
"tslint": "^5.11.0",
"tslint-config-prettier": "^1.17.0",
"tslint-config-standard": "^8.0.1"
},
"scripts": {
Expand All @@ -45,6 +47,7 @@
"lint-staged": {
"*.{js,ts}": [
"tslint --fix -c tslint.json",
"prettier --write",
"git add"
]
},
Expand Down
24 changes: 14 additions & 10 deletions src/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@

export const getContext = (width, height) => {
const getContext = (width, height) => {
const canvas = document.createElement('canvas')
canvas.setAttribute('width', width)
canvas.setAttribute('height', height)
return canvas.getContext('2d')
}

export const getImageData = (src: string, scale: number = 1): Promise<Uint8ClampedArray> => {
export function getImageData(
src: string,
scale: number = 1
): Promise<Uint8ClampedArray> {
const img = new Image()
src = src || img.src

Expand All @@ -15,7 +17,7 @@ export const getImageData = (src: string, scale: number = 1): Promise<Uint8Clamp
if (src.startsWith('data')) img.crossOrigin = 'Anonymous'

return new Promise((resolve, reject) => {
img.onload = function () {
img.onload = function() {
const width = img.width * scale
const height = img.height * scale
const context = getContext(width, height)
Expand All @@ -25,16 +27,17 @@ export const getImageData = (src: string, scale: number = 1): Promise<Uint8Clamp
resolve(data)
}

const errorHandler = () => reject(new Error('An error occurred attempting to load image'))
const errorHandler = () =>
reject(new Error('An error occurred attempting to load image'))

img.onerror = errorHandler
img.onabort = errorHandler
img.src = src
})
}

export const getCounts = (data: Uint8ClampedArray, ignore: string[]): [] => {
const countMap = {}
export function getCounts(data: Uint8ClampedArray, ignore: string[]): [] {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@a-hariti What's the thinking behind changing this to a function?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TLDR it is a matter of preference.
I think it is more readable IMHO, arrow functions are more suitable for one-liners like someNumbers.map(n => n*2), but once a functions get as big as this one, it becomes more difficult to keep track of the one you are reading.

let countMap = {}

for (let i = 0; i < data.length; i += 4 /* 4 gives us r, g, b, and a*/) {
let alpha: number = data[i + 3]
Expand All @@ -46,9 +49,10 @@ export const getCounts = (data: Uint8ClampedArray, ignore: string[]): [] => {
// skip undefined data
if (rgbComponents.indexOf(undefined) !== -1) continue

let color: string = alpha && alpha !== 255
? `rgba(${[...rgbComponents, alpha].join(',')})`
: `rgb(${rgbComponents.join(',')})`
let color: string =
alpha && alpha !== 255
? `rgba(${[...rgbComponents, alpha].join(',')})`
: `rgb(${rgbComponents.join(',')})`

// skip colors in the ignore list
if (ignore.indexOf(color) !== -1) continue
Expand Down
20 changes: 11 additions & 9 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
import {
getImageData,
getCounts
} from './helpers'
import { getImageData, getCounts } from './helpers'

interface Opts {
ignore?: string[]
Expand All @@ -11,20 +8,25 @@ interface Opts {

const defaultOpts: Opts = {
ignore: [],
scale: 1
scale: 1,
}

export default async function (src: string, opts: Opts = defaultOpts): Promise<{ color: string, count: number }[] > {
export default async function(
src: string,
opts: Opts = defaultOpts
): Promise<{ color: string; count: number }[]> {
opts = { ...defaultOpts, ...opts }

const {
ignore, // for example, to ignore white and black: [ 'rgb(0,0,0)', 'rgb(255,255,255)' ]
scale // 0 = best performance, lowest fidelity
// 1 = best fidelity, worst performance
scale, // 0 = best performance, lowest fidelity
// 1 = best fidelity, worst performance
} = opts

if (scale > 1 || scale <= 0) {
console.warn(`You set scale to ${scale}, which isn't between 0-1. This is either pointless (> 1) or a no-op (≤ 0)`)
console.warn(
`You set scale to ${scale}, which isn't between 0-1. This is either pointless (> 1) or a no-op (≤ 0)`
)
}

const data = await getImageData(src, scale)
Expand Down
4 changes: 2 additions & 2 deletions tests/global-setup.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
const { setup: setupDevServer } = require('jest-dev-server')

module.exports = async function globalSetup () {
module.exports = async function globalSetup() {
await setupDevServer({
command: `static-server ./tests/images --debug`,
launchTimeout: 50000,
port: 9080
port: 9080,
})
}
2 changes: 1 addition & 1 deletion tests/global-teardown.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const { teardown: teardownDevServer } = require('jest-dev-server')

module.exports = async function globalTeardown () {
module.exports = async function globalTeardown() {
await teardownDevServer()
}
21 changes: 12 additions & 9 deletions tests/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,17 @@ import analyze from '../src/index'
const green = 'rgb(126,211,33)'
const red = 'rgb(255,0,0)'


it('tests error with images', () => {
const img = ''
expect.assertions(1);
return expect(analyze(img)).rejects.toEqual(new Error('An error occurred attempting to load image'));
});

expect.assertions(1)
return expect(analyze(img)).rejects.toEqual(
new Error('An error occurred attempting to load image')
)
})

it('gets colors for base64 encoded images', async () => {
const img = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAYAAAA7MK6iAAAAAXNSR0IArs4c6QAAAGhJREFUSA3t0rENgCAABVFxEwdgRRNmZABGEWsoPsWVZ6f5OZMH5e3Pdy1Pq2P5wr/efPKs6I/PnIBV+W/WdrmAbkx4xpGIGkhNScaO1JGIGkhNScaO1JGIGkhNScaO1JGIGkhNScbOBKiIBjchGZzYAAAAAElFTkSuQmCC'
const img =
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAYAAAA7MK6iAAAAAXNSR0IArs4c6QAAAGhJREFUSA3t0rENgCAABVFxEwdgRRNmZABGEWsoPsWVZ6f5OZMH5e3Pdy1Pq2P5wr/efPKs6I/PnIBV+W/WdrmAbkx4xpGIGkhNScaO1JGIGkhNScaO1JGIGkhNScaO1JGIGkhNScbOBKiIBjchGZzYAAAAAElFTkSuQmCC'
const result = await analyze(img)

expect(result[0].count).toEqual(875)
Expand All @@ -35,7 +36,7 @@ it('gets colors for images with a source', async () => {

it('ignores a given color for images with a source', async () => {
const img = 'http://localhost:9080/dominant-red-secondary-green.png'
const ignoreColors = [ 'rgb(255,0,0)']
const ignoreColors = ['rgb(255,0,0)']
const result = await analyze(img, { ignore: ignoreColors })

expect(result[0].count).toEqual(25)
Expand Down Expand Up @@ -68,7 +69,8 @@ it('works with jpgs', async () => {
})

it('gets colors for images with semi transparency', async () => {
const img = 'http://localhost:9080/dominant-red-secondary-green-transparent.png'
const img =
'http://localhost:9080/dominant-red-secondary-green-transparent.png'
const result = await analyze(img)

expect(result[0].count).toEqual(875)
Expand All @@ -79,7 +81,8 @@ it('gets colors for images with semi transparency', async () => {
})

it('skips fully transparent pixels', async () => {
const img = 'http://localhost:9080/dominant-red-secondary-green-mostly-transparent.png'
const img =
'http://localhost:9080/dominant-red-secondary-green-mostly-transparent.png'
const result = await analyze(img)

expect(result[0].count).toEqual(4)
Expand Down
3 changes: 2 additions & 1 deletion tslint.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
{
"defaultSeverity": "error",
"extends": [
"tslint-config-standard"
"tslint-config-standard",
"tslint-config-prettier"
],
"jsRules": {},
"rules": {},
Expand Down