Skip to content

Commit

Permalink
vsprintf support
Browse files Browse the repository at this point in the history
  • Loading branch information
joseluisq committed Jul 26, 2018
1 parent b018976 commit 567cde6
Show file tree
Hide file tree
Showing 9 changed files with 139 additions and 23 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,5 @@ lib
/*.map
/*.d.ts
.*_cache
!/*.config.js
!/*.conf.js
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ sprintf('date: %s-%s-%s', 2018, 07, 25)

### vsprintf

Operates as `vsprintf()` but accepts an array of arguments.
Operates as `sprintf()` but accepts an array of arguments.

```js
import { vsprintf } from 'sprintfit'
Expand Down
38 changes: 38 additions & 0 deletions karma.conf.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
const realBrowser = String(process.env.BROWSER).match(/^(1|true)$/gi)
const travisLaunchers = {
chrome_travis: {
base: 'Chrome',
flags: ['--no-sandbox']
}
}

const localBrowsers = realBrowser ? Object.keys(travisLaunchers) : ['Chrome']

module.exports = (config) => {
const env = process.env['NODE_ENV'] || 'development'

config.set({
frameworks: ['jasmine', 'karma-typescript'],
plugins: [
'karma-jasmine',
'karma-typescript',
'karma-chrome-launcher',
'karma-jasmine-html-reporter',
'karma-spec-reporter'
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
files: [{ pattern: 'src/**/*.ts' }, { pattern: 'test/**/*.spec.ts' }],
preprocessors: {
'**/*.ts': ['karma-typescript'],
'test/**/*.spec.ts': ['karma-typescript']
},
reporters: ['progress', 'kjhtml'],
colors: true,
logLevel: env === 'debug' ? config.LOG_DEBUG : config.LOG_INFO,
autoWatch: true,
browsers: localBrowsers,
singleRun: false
})
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
"jasmine": "^3.1.0",
"jasmine-core": "^3.1.0",
"jasmine-spec-reporter": "^4.2.1",
"karma": "^2.0.4",
"karma": "^2.0.5",
"karma-chrome-launcher": "^2.2.0",
"karma-jasmine": "^1.1.2",
"karma-jasmine-html-reporter": "^1.2.0",
Expand Down
27 changes: 27 additions & 0 deletions rollup.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { name } from "./package.json";
import typescript from "rollup-plugin-typescript2";
import { terser } from "rollup-plugin-terser";

export default {
input: 'src/index.ts',
name,
output: {
file: `./${name}.umd.min.js`,
format: 'umd',
sourcemap: false,
exports: 'named'
},
plugins: [
typescript(),
terser()
],
onwarn
}

function onwarn(message) {
const suppressed = ['UNRESOLVED_IMPORT', 'THIS_IS_UNDEFINED']

if (!suppressed.find((code) => message.code === code)) {
return console.warn(message.message)
}
}
60 changes: 42 additions & 18 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,41 +1,65 @@
const chars = 's'

/**
* Return a formatted string and accepts a variable number of arguments.
* Return a formatted string using an array of arguments
*
* @param args array of arguments
* @returns a formatted string
*/
export function sprintf (...args: any[]): string {
const len: number = args.length
const format: string = (args[0] || '').toString()
const argv: any[] = len > 0 ? new Array(len - 1) : []
function sprintfv (args: any[]): string {
const argsLen: number = args.length
const formatv: string = (args[0] || '').toString()
const argv: any[] = []
const argvLen: number = argsLen > 0 ? argsLen - 1 : 0

// TODO: type specifier '%s' supported only
const formats = format.split(`%${chars}`)
// Notice: type specifier '%s' is only supported
const formats: string[] = formatv.split('%s')
const formatsLen: number = formats.length

if (formats.length <= 0) {
return format
if (formatsLen <= 0) {
return formatv
}

const times = formats.length - 1
const formatLen: number = formatsLen - 1

if (times > argv.length) throw new Error('Too few arguments supplied.')
if (formatLen > argvLen) {
throw new Error('Too few arguments supplied.')
}

for (let i = 0; i < len - 1; ++i) {
argv[i] = (args[i + 1] || '').toString()
for (let i = 0; i < argsLen - 1; ++i) {
argv.push(
(args[i + 1] || '').toString()
)
}

let str = ''

for (let i = 0; i < formats.length; i++) {
for (let i = 0; i < formatsLen; i++) {
str += formats[i] || ''

if (i < times) {
if (i < formatLen) {
str += argv[i] || ''
}
}

return str
}

export default sprintf
/**
* Return a formatted string and accepts a variable number of arguments
* whose first argument correspond to string format
*
* @returns a formatted string
*/
export function sprintf (...args: any[]): string {
return sprintfv(args)
}

/**
* Operates as `sprintf()` but accepts an array of arguments
*
* @param format string format
* @param argsv an array of arguments
* @returns a formatted string
*/
export function vsprintf (format: any = '', argsv: any[] = []): string {
return sprintfv([ format ].concat(argsv))
}
4 changes: 2 additions & 2 deletions test/sprintf.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@ describe('sprintf', () => {
.toThrowError('Too few arguments supplied.'))
it('format with one argument', () => expect(sprintf('Hello %s', 'world!'))
.toBe('Hello world!'))
it('format with too much arguments', () => expect(sprintf('foo %s', 'bar', 'baz'))
it('format with many arguments', () => expect(sprintf('foo %s', 'bar', 'baz'))
.toBe('foo bar'))
it('format arguments (middle)', () => expect(sprintf('a %s c %s e %s g', 'B', 'D', 'F'))
.toBe('a B c D e F g'))
it('format arguments (left)', () => expect(sprintf('%s b %s d %s f %s', 'A', 'C', 'E', 'G'))
.toBe('A b C d E f G'))
it('string', () => expect(sprintf('Hi:%s', [])).toBe('Hi:'))
it('string with array of args', () => expect(sprintf('Hi:%s', [])).toBe('Hi:'))
})
25 changes: 25 additions & 0 deletions test/vsprintf.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { vsprintf } from '../src'

describe('vsprintf', () => {
it('undefined', () => expect(vsprintf()).toBe(''))
it('null', () => expect(vsprintf(null)).toBe(''))
it('empty', () => expect(vsprintf('')).toBe(''))
it('array', () => expect(vsprintf([ 1, 2, 3 ])).toBe('1,2,3'))
it('object', () => expect(vsprintf({})).toBe('[object Object]'))
it('true', () => expect(vsprintf(true)).toBe('true'))
it('false', () => expect(vsprintf(false)).toBe(''))
it('void 0', () => expect(vsprintf(void 0)).toBe(''))
it('string', () => expect(vsprintf('Hello')).toBe('Hello'))
it('format with no arguments', () => expect(() => vsprintf('Hello %s'))
.toThrowError('Too few arguments supplied.'))
it('format with no arguments explicit', () => expect(() => vsprintf('Hello %s', []))
.toThrowError('Too few arguments supplied.'))
it('format with one argument', () => expect(vsprintf('Hello %s', [ 'world!' ]))
.toBe('Hello world!'))
it('format with many arguments', () => expect(vsprintf('foo %s', [ 'bar', 'baz' ]))
.toBe('foo bar'))
it('format arguments (middle)', () => expect(vsprintf('a %s c %s e %s g', [ 'B', 'D', 'F' ]))
.toBe('a B c D e F g'))
it('format arguments (left)', () => expect(vsprintf('%s b %s d %s f %s', [ 'A', 'C', 'E', 'G' ]))
.toBe('A b C d E f G'))
})
2 changes: 1 addition & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2113,7 +2113,7 @@ karma-typescript@^3.0.13:
util "^0.10.3"
vm-browserify "0.0.4"

karma@^2.0.4:
karma@^2.0.5:
version "2.0.5"
resolved "https://registry.yarnpkg.com/karma/-/karma-2.0.5.tgz#3710c7a2e71b1c439313f283846d88e04e4f918c"
dependencies:
Expand Down

0 comments on commit 567cde6

Please sign in to comment.