Skip to content

Instantly share code, notes, and snippets.

@MichalZalecki MichalZalecki/utils.js
Last active Nov 29, 2017

Embed
What would you like to do?
Native implementation of common helper functions
function toPairs(obj) {
return Object.entries(obj); // ES2017
}
describe("toPairs", () => {
it("transforms object to key-value pairs", () => {
expect(toPairs({ foo: "bar", foz: "baz" })).toEqual([
["foo", "bar"],
["foz", "baz"]
]);
});
});
function fromPairs(arr) {
return arr.reduce((akk, [k, v]) => ({ ...akk, [k]: v }), {});
}
describe("fromPairs", () => {
it("transforms pairs to an object", () => {
expect(fromPairs([["foo", "bar"], ["foz", "baz"]])).toEqual({
foo: "bar",
foz: "baz"
});
});
});
function range(start, end) {
return [...Array(end - start)].map((v, i) => i + start);
}
describe("range", () => {
it("returns a range of numbers", () => {
expect(range(1, 5)).toEqual([1, 2, 3, 4]);
expect(range(0, 4)).toEqual([0, 1, 2, 3]);
expect(range(-1, 3)).toEqual([-1, 0, 1, 2]);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.