Skip to content

Commit

Permalink
feat: Passing charcode (integer) to %c will now convert to correct ch…
Browse files Browse the repository at this point in the history
…aracter [BREAKING].

Signed-off-by: Johannes Tegnér <[email protected]>
  • Loading branch information
Johannestegner committed Oct 13, 2022
1 parent 99bc486 commit bb30e8c
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 9 deletions.
13 changes: 5 additions & 8 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
'use strict';
import hasOwn from 'core-js/actual/object/has-own';

/**
* Sprintf - String Print Format.
Expand Down Expand Up @@ -163,6 +164,10 @@ const types = {
},
/* Char */
c: (val) => {
if (val?.constructor?.name === 'Number') {
val = String.fromCharCode(val);
}

val = String(val);
return val.length <= 0 ? '[NULL]' : val[0];
},
Expand All @@ -175,11 +180,3 @@ const types = {
j: (val) => JSON.stringify(val)
};

const hasOwn = (object, key) => {
if (Object.hasOwn) {
return Object.hasOwn(object, key);
}

// eslint-disable-next-line no-prototype-builtins
return object.hasOwnProperty(key);
};
10 changes: 9 additions & 1 deletion test/sprintf.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import sprintf from '../src/index';

describe('Tests for sprintf.', () => {
test('Returns format if no substitutions.', () => {
expect(sprintf('Abc,123', 123, 455454)).toBe('Abc,123');
});

describe('Tests for variable substitution.', () => {
describe('Integer types', () => {
describe('Precision / pad tests.', () => {
Expand Down Expand Up @@ -179,11 +183,15 @@ describe('Tests for sprintf.', () => {

test('Char', () => {
expect(sprintf('Abc %c EFG', 'A')).toBe('Abc A EFG');
expect(sprintf('Abc %c %c %c %c EFG', 5, '9', 'T', 'g')).toBe('Abc 5 9 T g EFG');
expect(sprintf('Abc %c %c %c %c EFG', '5', '9', 'T', 'g')).toBe('Abc 5 9 T g EFG');
expect(sprintf('Abc %c %c EFG', '5')).toBe('Abc 5 %c EFG');
expect(sprintf('Abc %c %c %c EFG', '5', 'abc', '')).toBe('Abc 5 a [NULL] EFG');
});

test('Char (code)', () => {
expect(sprintf('%c %c %c %c', 8482, 0xd6, 33, 0x39)).toBe('™ Ö ! 9');
});

test('Json', () => {
expect(sprintf('Abc %j EFG', { test: 'A' })).toBe('Abc {"test":"A"} EFG');
expect(sprintf('Abc %j %j %j %j EFG', 5, {
Expand Down

0 comments on commit bb30e8c

Please sign in to comment.