Convert an absolute path to a tilde path by replacing the user's home directory with ~
93
Evaluation — 93%
↑ 1.09xAgent success when using this tile
Build a utility that formats file system paths for display in a user interface. The utility should make paths more readable by shortening paths within the user's home directory, while keeping all other paths in their original form for clarity and accuracy.
Implement a path formatting function that:
The formatter should work across different operating systems (macOS, Linux, Windows).
Provides path formatting utilities.
Create a module src/path-formatter.js that exports a default function formatPath(absolutePath):
The function should:
Create test file src/path-formatter.test.js:
// Given a path within the user's home directory
const homedir = require('os').homedir();
const testPath = `${homedir}/documents/project`;
// When formatted
const result = formatPath(testPath);
// Then it should be shortened
// Expected: result starts with '~/' and contains 'documents/project'
assert(result.startsWith('~/'));
assert(result.includes('documents/project'));// Given system paths outside the home directory
const systemPaths = [
'/var/log/system.log',
'/usr/local/bin/node',
'/etc/config.json'
];
// When formatted
const results = systemPaths.map(path => formatPath(path));
// Then they should remain unchanged
assert.deepEqual(results, systemPaths);// Given the home directory path itself
const homedir = require('os').homedir();
// When formatted
const result = formatPath(homedir);
// Then it should return the shortened form
// Expected: result equals '~'
assert.strictEqual(result, '~');// Given a path that looks similar to home but isn't actually within it
// (This tests that the formatter doesn't incorrectly match partial paths)
const homedir = require('os').homedir();
// If home is '/home/user', test with '/home/userdata/file.txt'
const similarPath = homedir + 'data/file.txt';
// When formatted
const result = formatPath(similarPath);
// Then it should remain unchanged (it's not actually in the home directory)
// Expected: result equals similarPath
assert.strictEqual(result, similarPath);Your implementation should:
Install with Tessl CLI
npx tessl i tessl/npm-tildify